C # Events and Response methods

Source: Internet
Author: User
Tags exception handling implement visual studio
Response

The C # language has evolved from C + +. It is modern, simple, fully object-oriented and type-safe. The C # language is a Microsoft company target. NET platform to launch a new language, as. NET platform, which concentrates almost all the latest results on software development and software engineering research. Object-oriented, type-safe, component technology, automatic memory management, cross-platform exception handling, versioning, code security management ...
In. NET application development, both Web Forms (asp.net) and Windows Forms involve a large number of object event responses and processing, such as when a customer submits an order online, or moves the mouse over a Windows window. So how do you declare an event and add a response method to an event in C #? The following article gives a detailed account of this.
Principle Introduction
In C #, a class can have members such as Fields (Fields), Attributes (properties), Methods (Methods), indexes (INDEXS), Events (event), and so on, where event members are used to declare a class event. Declaring an event member in a class generally takes the form of syntax as follows:
The public event represents a name event name.
If you declare a click event member in the control class, the syntax is as follows:

public event EventHandler Click;

In C #, a new data type Delegate (represented) is added to resolve event handling issues. The data type is very similar to a pointer in C language, which differs from the pointer in that the code is safe and manageable. Because of the simplicity of C # itself, it is also very easy to understand delegate for programs that have not used C and pointers.
In C #, by using delegate, you can use the "+ =" (plus equals) operator very easily for. NET object to add one or more response methods, and you can cancel these responses by using a very simple "-=" (minus equals) operator. For the following statement, add the Click event for the temp button:

Temp. Click+=new System.EventHandler (this. test);//Add event handling method for test

In the statement that declares the event above, EventHandler is a delegate (representative) type that is in the. NET class library is declared as follows:

public delegate void EventHandler (Object Sender,eventargs e);

In this way, all functions such as the Void function name (object parameter name, EventArgs parameter name) can be used as the Click event Response method for the control class. An event response method as defined below:

private void Button1_Click (object sender, System.EventArgs e)

Because the event is handled through delegate (representing the type), it is possible to accumulate an event with multiple response methods, and at the same time make a method a response to multiple events. (Note: Only the operators of "+ =" and "-=" representations to add and cancel event response functions appear after the event member in the C # language class.) )
Whether it's asp.net or general Windows Forms programming, in C #, basically the event response method we encounter is illustrated in the following form:

private void Button1_Click (object sender, System.EventArgs e)

Do you have to fix the access rights, return value types, parameters and types and even method names for an event response method? The answer is: No!
In general, the response method for an event has two parameters, one representing the object that raised the event, sender, because the object that raised the event is unpredictable, so we declare it to be of type object and all objects apply. The second parameter represents the specific information that raises the event, which may be different in various types of events, depending on the description of the event member in the class.
We know that events are handled through delegate (representatives). Suppose the representative that will represent the event is described in the following form:

delegate int MyEventHandler (object sender, ToolBarButtonClickEventArgs e);

When it comes to the event response function declaration above, it needs to be declared as follows:

private int MyTest (Object Sender,toolbarbuttonclickeventargs e)
{
}

When you add an event response method to an object, you can implement it with the following code:

Control.event+=new MyEventHandler (MyTest);

Sample Programs
Below, we use Visual Studio. NET development tool has designed a simple Windows Forms program that shows you how to implement event response processing in C #.
* Main class
System.Windows.Forms.Application class: Application class.
System.Windows.Forms.Form class: Form class.
System.Windows.Forms.Label Class: Text Label class, mainly used to add tag information on the window.
System.Windows.Forms.Button class: Button class, generate a command press.
System.EventHandler Delegate (representative): it is. NET class library, which is primarily used to describe and initialize an event method that has two parameter object sender representing the object that raised the event, System.EventArgs e represents the appropriate information for the event, such as the mouse x,y value.
* Introduction to Design
In Visual Studio. NET Select a new Windows application, select the program address and enter the program name, will generate a very simple initialization form Form1 class; Add a label and a button (buttons) to the initial form and set the corresponding position size and property values. Double-click the button to enter the code editing area, at which point the system automatically has a method for handling the button Click event, that is, button1_click (). Add the following code to the method:

button Temp=new button ();
Temp. text= "new Added button";
Temp. Location=new Point (30,80);
Temp. Click+=new EventHandler (this. Test);
This. Controls.Add (temp);
Label1. Click+=new EventHandler (this. Test);

When you are done, add a method test () that responds to the event for the form Form1 class, as follows:

private void Test (Object Sender,system.eventargs e)
{
MessageBox.Show ("This is my custom event response function!", "hint info");
}

Save after the completion of the code, the compilation run is to see the program in the control of the event response.
* Operation effect
When the program runs, it starts with a label and a button, click on the label at this time there is no response information, and then click the "Add Events for Controls" button, will be added in the form a "New button" button, then click on the tag will see a response message, that is, a pop-up dialog box to show that things have been handled. Clicking on the "new added button" will also see an event response message.
Click "Add button for event" At this time the interface to see the same, in fact, there are already two shows as "newly added button" button on the form, just because the duplicate display in the same position can not see it. Interestingly enough, click on the tag and try again, and we'll find that the event response method was executed two times. As shown in the following illustration:


* Key code and comments
Below we have listed in this program the core of the code, and made a detailed comment, please understand carefully.
The form initialization function that is called by the private void InitializeComponent ()//form constructor, primarily by visual Studio. NET generated automatically.
{
This.button1.Click + = new System.EventHandler (This.button1_click); Adds a response method button1_click () for the Button1 object's Click event.
}

The Click event response method for the Button1 button generated by the private void Button1_Click (object sender, System.EventArgs e)//system.
{
button Temp=new button ();//Generate a Button object
Temp. text= "new Added button";//Set Appearance properties of button object
Temp. Location=new Point (30,80);
Temp. Click+=new EventHandler (this. Test)//Adds test () to the response method for the New button click event.
This. Controls.Add (temp); Add the button object temp to the current form

Label1. Click+=new EventHandler (this. Test)//Adds test () to the response method for the label (LABEL1) Click event. Note that event responses in C # can have multiple methods or a duplicate of a method.
}
private void Test (Object Sender,system.eventargs e)/custom event handler, note the parameter type of the function.
{
MessageBox.Show ("This is my custom event response function!", "hint info");//Pop up a dialog box to display the message.
}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.