If you're familiar with Windows C development, you will understand the idea of handling messages as they arrive by the action of the WndProc switch statement. If you have been working with MFC, you will know that messages are routed through the message map of your application. Under .NET the message routing system is provided by delegates. Your application will define event handlers that are called through a delegate whenever a message arrives. Button clicks for example, can be handled by using a generic EventHandler delegate. Other types of events, such as mouse events or timer events, are serviced through specific handlers that have their own delegate signatures.
Adding a button to the Windows Forms application is simple. You can add a button member to the class, initialize it in the constructor, and place it in the controls collection.
When this is done, you can wire up an event that is trapped whenever the button is clicked. Events sent through the system are hooked to event handlers of a specific signature by a multicast delegate that is declared especially for this purpose. Your event handlers must all have the following method signature:
void EventMethodName(Object sender, EventArgs e);
Event handlers are added to the control's event sources with the += operator and removed with the -= operator, so events can be modified dynamically at runtime. Because events are multicast, you can add more than one handler at a time to the same event.
Listing 3.1.3 shows the modified file HWFButton.cs.
Type in Listing 3.1.3 and build it with the build batch file. Running the sample will show a window that has the same message and a clickable button. The button handler simply swaps the text in the label control to verify that the handler worked.
NOTE
Note that the code in Listing 3.1.3 uses the fully qualified name for the components and methods:
button1.Size = new System.Drawing.Size(408,25);
This longhand form is not always necessary. You could abbreviate the line above to
button1.Size = new Size(408,25);
Layout tools will always give you the longhand version because they never get tired of typing.
Generally, if the object you're creating is in a namespace you declared you were using, you can use the shorthand.
When you run the file, you will see the application shown in Figure 3.1.2.
18.118.137.7