C # events (event) resolution [GO]

Source: Internet
Author: User

event, this word for beginners, often always seem a little mysterious, difficult to understand. And these things are often used in programming and very important things. We all know the importance of the Windows message processing mechanism, in fact, the C # event is based on the Windows message processing mechanism, but the encapsulation is better, so that developers need not know the underlying message processing mechanism, can develop a powerful event-based application.

Let's take a look at the benefits of event programming.
In the past we wrote such programs, often using the wait mechanism, in order to wait for something to happen, the need to constantly detect some of the judgment variables, and the introduction of event programming, greatly simplifies the process:
-Use events to make it easy to determine the order in which programs are executed.
-When an event driver waits for an event, it does not consume a lot of resources. The biggest difference between an event driver and a procedural program is that the program no longer checks the input device, but stays still, waits for the message to arrive, and each incoming message is queued and waits for the program to process it. If no messages are waiting, the program returns control to the operating system to run other programs.
-Events simplify programming. The operating system simply passes the message to the object, which determines how the event is handled by the object's event driver. The operating system does not have to know how the program works inside, but it needs to know how to talk to the object, that is, how to deliver the message.

With so many benefits, it seems that we really need to master it. As the saying goes: "No, it will not be difficult." Let's start with a step-by-step ...

To tell an event, it is necessary to refer to the Commission (delegate). The relationship between them can be illustrated by an obvious analogy, which may not be quite appropriate. For example, you want to rent a house, this is an event, then the Commission is a housing leasing intermediary, when you rent the house news to inform the intermediary, the intermediary will produce a set of requirements to meet your housing leasing scheme. Then by the intermediary to carry out this package, you can rent this House, that the incident was dealt with. Of course, you can also not through the intermediary, directly to the landlord, but if there is no Internet tools, how do you get the information about who rented the house. The topic is far away.

Delegate (delegate)
A delegate can be understood as a function pointer, unlike a delegate that is object oriented and type-safe. About the delegation of understanding, you can refer to my another article, "C # Commissioned by the personal understanding."

Events (Event)
We can simply divide the event programming into two parts: the class that the event takes place (the written one called the event generator) and the class that the event receives processing. The class in which the event occurs means that an event is triggered in this class, but the class does not know which object or method will receive and handle the event that it triggers. What is needed is a medium between the sender and the receiver. This medium is the delegate (delegate) in the. NET framework. In the class where event reception is handled, we need to have a way of handling events. OK, so we're going to implement a program that captures keyboard keys in this order, step-by-step instructions on how to write an event application.

1. First, create a EventArgs class of your own.
Quote from MSDN:
EventArgs is the base class for classes that contain event data, and this class does not contain event data, which is used by events that do not pass state information to an event handler when an event is raised. If the event handler requires state information, the application must derive a class from this class to hold the data.
Because in our keyboard key event to include key information, so to derive a KeyEventArgs class, to save the key information, so that the following know what button pressed.

Internal class Keyeventargs:eventargs
{
Private char Keychar;
Public KeyEventArgs (char Keychar): Base ()
{
This.keychar = Keychar;
}

Public Char Keychar
{
Get
{
return Keychar;
}
}
}

[NextPage]
2. Create an event class Keyinputmonitor that monitors the input of keyboard keys and triggers an event:

Internal class Keyinputmonitor
{
Create a delegate with a return type of void, two parameters
public delegate void KeyDown (object sender, KeyEventArgs e);
Associates the created delegate with a specific event where the specific event is onkeydown
public event KeyDown OnKeyDown;

public void Run ()
{
bool finished = false;
Todo
{
Console.WriteLine ("Input a char");
String response = Console.ReadLine ();

Char Responsechar = (Response = = "")? ': Char. ToUpper (Response[0]);
Switch (Responsechar)
{
Case ' X ':
Finished = true;
Break
Default
Get the parameters of the key information
KeyEventArgs KeyEventArgs = new KeyEventArgs (Responsechar);
Triggering events
OnKeyDown (this, KeyEventArgs);
Break
}
}while (!finished);
}
}

Notice here the onkeydown (this, KeyEventArgs); a sentence that triggers the event, and the event is handled by the KeyDown delegate, which delegates the event-handling method to handle the event, which is the class of the event receiver. Parameter this is the object that triggers the event, and the KeyEventArgs contains the key information.

3, the end of the class to create an event receiver, this class will first produce a delegate instance, and then add this delegate instance to the event list generated event objects, this process is called subscription events. A method is then provided to echo the key information.

     internal class Eventreceiver
    {
         Public eventreceiver (Keyinputmonitor monitor)
        {
           //Generates a delegate instance and adds it to the list of events generated by Keyinputmonitor
            Monitor. OnKeyDown + = new Keyinputmonitor.keydown (this. Echo);
       }
        private void Echo (object sender, KeyEventArgs e)
         {
           // Real event-handling functions
            Console.WriteLine ("Capture key: { 0} ", E.keychar);
       }
   }

[NextPage]
4, look at how to call

public class Mainentrypoint
{
public static void Start ()
{
Instantiating an event dispatcher
Keyinputmonitor monitor = new Keyinputmonitor ();
Instantiating an event receiver
Eventreceiver eventreceiver = new Eventreceiver (monitor);
Run
Monitor. Run ();
}
}

Summarize:

The steps needed to use the event in C #:
1. Create a delegate
2. Associates the created delegate with a specific event (. NET class Library Many of the events are already customized, so they have a corresponding delegate, in writing the associated event handler-that is, when there is an event occurs when we want to execute the method we need to have the same signature with this delegate.
3. Write an event handler
4. Using the written event handler to generate a delegate instance
5. Add this delegate instance to the event list that produces the event object, which is also called subscription events

The process of event generation and implementation in C #:
1. Define a as an instance of an event, A is an event generated by a
2. Define B as the instance that receives the event, and B is the method of handling the event
3.A the user (program creator or program user) or system produces a event (e.g. click a button to produce a click event)
4.A notifies this event to B through a delegate object in the event list
5.B received an event notification (actually b.b using a delegate to implement the event's reception)
6. Call the B.b method to complete event handling

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.