Writing Event Handlers

As a user interacts with a Windows Forms application, events are triggered by the user's keyboard and mouse activities. (There are events triggered by other happenings as well, but in this section only user activities are relevant.) For example, when the user clicks the mouse while it is over a button, the button's Click event occurs. This is the most important event for a button: It's unusual for you to write code to deal with lesser events like "the mouse has been moved above the button" or "this control has just lost focus" on a button.

When an event occurs over a particular control, the system checks to see if the control has a handler for that event. If it does, the event handler is called. An event handler is a void function that takes a pointer to a System::Object and a pointer to a System::EventArgs . The System::Object is the control over which the event occurred, and the System::EventArgs contains more details about the event, such as the mouse coordinates or whether Shift, Ctrl, or Alt were pressed. As often as not, developers ignore both of these arguments: If you're writing a handler for a click on button1 , you don't need to check the first argument to know this is button1 , and you don't need to know if someone held Shift while they clicked the button. However, for those handlers that need it, the information is always available.

Adding an Event Handler

There are two ways to add a handler to an event. The simplest is to double-click the control in the designer. This adds a handler to the default event, which varies from control to control. For example, double-clicking the Go button in this sample adds this function to the class:

 private: System::Void button1_Click(System::Object *  sender,                                     System::EventArgs *  e) { } 

That's because Click is a button's default event. It also adds this line to InitializeComponent :

 this->button1->Click += new System::EventHandler(this, button1_Click); 

This line ensures the handler is called when the event occurs. Double-clicking the text box in the sample would add this event:

 private: System::Void textBox1_TextChanged(System::Object *  sender,                                            System::EventArgs *  e) { } 

It also adds a line to InitializeComponent that registers the handler. Table 4.1 lists the default events of the most popular controls.

Table 4.1. Controls and Their Default Events





















Writing the handler is as simple as filling code in to the function. Examples are in the next section.

To add a handler for another event, use the Properties window. Click the control, and then if the Properties window is not displayed, choose View, Properties Window. Look for the lightning bolt at the top of the Properties window (see Figure 4.9) and click it.

Figure 4.9. The Events button causes the Properties window to display events instead of properties.


At the top of the Properties window is a toolbar with five buttons: Categorized, Alphabetic, Properties, Events, and Property Pages. The first two control the way the properties are organized: By default and when Categorized is pressed, properties are organized into categories such as Appearance and Behavior. When Alphabetic is pressed, properties appear in alphabetical order. By default and when the Properties button is pressed, the Properties window displays properties. But when the Events button is pressed, it displays all the events that can occur for this particular control. (They appear in one long alphabetical list or divided into categories, depending on which of the first two buttons is pressed.) The final button, Property Pages, is enabled only when you are looking at the Properties window with the entire project or solution selected, and provides a quick shortcut to the project properties or solution properties. It's not enabled when a control is selected. Understanding and using this toolbar will make the Properties window a more productive part of the Visual Studio user interface.

For example, if you select the check box on the form in the sample application, the Events button in the Properties window lists all the events that can happen to a check box. Double-clicking to the right of an event adds a handler for that event and opens the editor, scrolled to the function that was just added.

Writing an Event Handler

Many event handlers are a single line long. For example, this pair of handlers is in the sample application for this chapter:

 private: System::Void checkBox1_MouseEnter(System::Object *  sender,                                            System::EventArgs *  e) {    checkBox1->BackColor = Color::AliceBlue; } private: System::Void checkBox1_MouseLeave(System::Object *  sender,                                            System::EventArgs *  e) {    checkBox1->BackColor = BackColor; } 

These handlers respond to the mouse entering the area of the check box and to it leaving that area. The MouseEnter handler changes the background color of the check box to AliceBlue and the MouseLeave handler restores it to the same background color as the form as a whole.

When writing an event handler, refer to the controls on the form using the same names , such as checkBox1 or textBox1 , that you see in the Name property when working with the form in the designer. If you change the name of a control in the designer, the code in InitializeComponent() will be edited to use the new name immediately, but other functions, such as your handlers, will not be edited. To simplify your life, make sure you are happy with the names of all the controls on your form before you start to write handlers for their events.


It's generally a bad idea to accept the names the designer generates for your controls. This chapter uses these default names to make it easier to follow along. But if you have three text boxes on a form, it's a lot easier to use the right one when they're called firstName , lastName , and employeeID than when they're called textBox1 , textBox2 , and textBox3 . Just remember to make these changes as you add the controls, rather than later when you'll have to change a lot of code to reflect the new names.

A more complicated event handler can interact with more than just a single control. The handler in Listing 4.1 displays a message box showing the values of the text box, check box, and radio buttons (see Figure 4.10). It also changes the image displayed in the picture box control.

Listing 4.1 Form1.h button1_Click()
 private: System::Void button1_Click(System::Object *  sender, System::EventArgs *  e) {     System::Text::StringBuilder* message = new System::Text::StringBuilder;     message->Append("Hello, ");     message->Append(textBox1->Text);     message->Append("!");     message->Append(Environment::NewLine);     message->Append("Optional box is ");     if (!checkBox1->Checked)         message->Append("not ");     message->Append("selected.");     message->Append(Environment::NewLine);     message->Append("Color chosen: ");     if (radioButton1->Checked)         message->Append("red");     else if (radioButton2->Checked)         message->Append("yellow");     else if (radioButton3->Checked)         message->Append("green");     else         message->Append("none");     message->Append(Environment::NewLine);     message->Append("Date selected: ");     message->Append(dateTimePicker1->Value.ToString());     message->Append(Environment::NewLine);     MessageBox::Show(message->ToString());     pictureBox1->Image = Image::FromFile(S"Winter.jpg"); } 
Figure 4.10. This chapter's sample application displays a message box demonstrating the values of its controls.


Some points to note about Listing 4.1:

  • The text message to be displayed in the message box is not built by adding strings directly, but instead with an instance of the StringBuilder class. The ToString() method of StringBuilder is used to extract the string that was built and pass it to MessageBox::Show at the end of the routine.

  • The Environment::NewLine constant is used to embed new line characters into the message. This is more readable and portable than C-style constants such as \r\n .

  • The Text property of the text box holds the characters the user typed before pressing the button.

  • The Checked property of the check box returns true if the box is checked and false if it is not.

  • There is no property of the group box to tell which radio button has been selected. Instead, use the Checked property of each radio button. By default, none is selected, so be sure your logic considers that possibility.

  • The Value property of the DateTime picker returns the date that the user chose as a DateTime structure. You must use the ToString method to convert it to a string that can be passed to the Append method of the StringBuilder .

  • The Image property of the picture box accepts an Image pointer. An easy way to get one is to use the static FromFile() method and pass in a filename. For this sample project, a number of image files are in the project folder for you to use.

Microsoft Visual C++. NET 2003 Kick Start
Microsoft Visual C++ .NET 2003 Kick Start
ISBN: 0672326000
EAN: 2147483647
Year: 2002
Pages: 141
Authors: Kate Gregory

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net