Analysis on C # event processing and custom events

Source: Internet
Author: User

1. Understand the predefined event processing mechanism in C #

Before writing code, familiarize yourself with the classes and delegation related to events in the. net Framework, and understand how to process pre-defined events in C.

EventArgs is the base class of the class containing event data, used to pass event details.

EventHandler is a delegate statement as follows:

Public delegate void EventHandler (object sender, EventArgs e)

Note that the parameter here, the former is an object (in fact, the reference of the object is passed here, if it is a click event of button1, then sender is button1 ), the following is the base class of the class that contains event data.

Next, let's take a look at the event declaration in the Button class (using the WinCV tool). The Click event is used as an example.

Public event EventHandler Click;

An EventHandler event Click is defined here.

The previous content is C # which has been defined for us in the class library. Next let's look at the code generated during programming.

Private void button#click (object sender, System. EventArgs e)
{
...
}

This is the method corresponding to the button#click event. Note that the parameters of the method comply with the signature in the delegate (both the parameter list ). Then how can we associate this method with the event? Please refer to the following code.

This. button1.Click + = new System. EventHandler (this. button#click );

Bind this. button#click method to this. button1.Click event.

Next, let's take a look at the C # event processing workflow. First, the system will create an object for us to listen to events in the background (if it is a button1 event, the event being listened to is button1 ), this object is used to generate events. If a user event occurs, the corresponding application event is generated, and all the methods for subscribing to the event are executed.

Ii. Simple custom events (1)

First, we need to define a class to listen to client events. Here we listen to keyboard input.

Define a delegate.

Public delegate void UserRequest (object sender, EventArgs e );

The previous object is used to pass the event occurrence, and the EventArgs is used to pass the event details. It is of no use now. It will be used in later examples.

The following defines an event of this delegate type.

Public event UserRequest OnUserRequest;

Let's create an endless loop.

Public void Run () {bool finished = false; do {if (Console. readLine () = "h") {OnUserRequest (this, new EventArgs () ;}} while (! Finished );}

This code constantly requires the user to enter characters. If the input result is h, the OnUserRequest event is triggered, and the event trigger is itself (this ), no event details (EventArgs instances with no parameters passed ). We name this class UserInputMonitor.

What we need to do below is to define the client class
First, you must instantiate the UserInputMonitor class.
UserInputMonitor monitor = new UserInputMonitor ();

Then we define a method.

Private void ShowMessage (object sender, EventArgs e)
{
Console. WriteLine ("HaHa !! ");
}

The last thing we need to do is to associate this method with the event (subscribe to the event) and write it into the constructor of the Library User class.

Client (UserInputMonitor m)
{
M. OnUserRequest + = new UserInputMonitor. UserRequest (this. ShowMessage );
// M. OnUserRequest + = new m. UserRequest (this. ShowMessage );

// Note that this writing method is incorrect because the delegate is static.

}

Create a client instance.

New Client (monitor );

By the way, don't forget to let monitor start listening to events.

Monitor. run ();

The Code is as follows:

Using System; class UserInputMonitor {public delegate void UserRequest (object sender, EventArgs e); // defines the delegate public event UserRequest OnUserRequest; // This delegate type event public void Run () {bool finished = false; do {if (Console. readLine () = "h") {OnUserRequest (this, new EventArgs () ;}} while (! Finished );}}

Public class Client {public static void Main () {UserInputMonitor monitor = new UserInputMonitor (); new Client (monitor); monitor. run ();} private void ShowMessage (object sender, EventArgs e) {Console. writeLine ("HaHa !! ");} Client (UserInputMonitor m) {m. onUserRequest + = new UserInputMonitor. userRequest (this. showMessage); // m. onUserRequest + = new m. userRequest (this. showMessage); // note that this writing method is incorrect, because the delegate is static }}
III. Further study on the predefined event processing mechanism in C #

Some events in C # may appear different from the previous ones. For example

Private void textBox1_KeyPress (object sender, System. Windows. Forms. KeyPressEventArgs e)
{

}

This. textBox1.KeyPress + = newSystem. Windows. Forms. KeyPressEventHandler (this. textbox#keypress );

KeyPressEventArgs is used here instead of EventArgs as the parameter. The KeyEventHandler delegate is used here, instead of the EventHandler delegate.

KeyPressEventArgs is the derived class of EventArgs, And the KeyEventHandler declaration is as follows:

Public delegate void KeyEventHandler (object sender, KeyEventArgs e );

Is the delegate that the parameter is KeyEventArgs. So why does the KeyPress event do this? We can find the answer from the constructor of two classes.

Public EventArgs ();

Public KeyPressEventArgs (char keyChar );

What is the keyData here? It is used to transmit the key we pressed.

I found another property in KeyEventArgs.

Public char KeyChar {get ;}

I further proved my theory. Let's take a similar example to help you understand it.

4. Simple custom events (2)

Use the example above to modify it.

We also define an EventArgs (similar to KeyEventArgs) named MyEventArgs, define a constructor public MyEventArgs (char keyChar), and set the corresponding attributes. The Code is as follows:

Using System; class MyMyEventArgs: EventArgs {private char keyChar; public MyMyEventArgs (char keyChar) {this. keychar = keychar;} public char KeyChar {get {return keyChar ;}}}

Because now we want to listen to multiple keys, we have to rewrite the do... while section of the listener class. Rewrite the delegate and rewrite the parameters passed by the client. The final code is as follows.

Using System; class MyEventArgs: EventArgs {private char keyChar; public MyEventArgs (char keyChar) {this. keyChar = keyChar;} public char KeyChar {get {return keyChar ;}}}

Class UserInputMonitor {public delegate void UserRequest (object sender, MyEventArgs e); // defines the delegate public event UserRequest OnUserRequest; // This delegate type event public void Run () {bool finished = false; do &

Related Article

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.