C # Event parsing

Source: Internet
Author: User

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

Let's start by looking at the benefits of event programming.
In the past we have written such programs, often using the wait mechanism, in order to wait for something to happen, we need to constantly detect some of the judgment variables, and introduced event programming, greatly simplifying the process:
-Using events makes it easy to determine the order in which the 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 input 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.
-the event simplifies programming. The operating system simply passes the message to the object, and the object's event driver determines how the event is handled. The operating system does not have to know the internal working mechanism of the program, just need 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: "Difficult will not, will be not 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 explained 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 put the information about renting a house to inform the intermediary, the intermediary will produce a suit to meet your requirements of the housing leasing program. Then by the intermediary to carry out the scheme, you can rent the house, that is, the incident was processed. Of course you can also not through the intermediary, directly to the landlord, but if there is no Internet and other tools, how do you get information about who rents 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. For the understanding of the delegation, you can refer to my other article "C # Delegated personal understanding".

Events (Event)
We can simply divide the event programming into two parts: the class in which the event occurs (called the event generator in writing) and the class that the event receives processing. The class in which an 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 it fires. What is needed is a medium between the sender and the receiver. This medium is delegated (delegate) in the. NET framework. In the class where the event is received, we need to have a way to handle the event. Well, let's follow this order to implement a program that captures the keyboard keys, step-by-step instructions on how to write the event application.

1, first create a own EventArgs class.
Quoted from MSDN:
EventArgs is the base class for the class that contains the event data, which does not contain event data and is used by events that do not pass state information to the event handler when the event is raised. If the event handler requires state information, the application must derive a class from this class to hold the data.

Because we want to include the key information in our keyboard key event, we want to derive a KeyEventArgs class to save the key information so that we know which key to press later.

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

Public Char KeyChar
{
Get
{
return KeyChar;
}
}
}


2. Create an event class Keyinputmonitor, which 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 Keydownhandler (object sender, KeyEventArgs e);
Associates the created delegate with a specific event, where the specific event is KeyDown
public event Keydownhandler KeyDown;

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

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


Note here that KeyDown (this, KeyEventArgs) is, this is the statement that triggered the event, and the event is referred to the Keydownhandler delegate to handle, the delegate specifies the event handling method to handle the event, this is the event receiver's class thing. The parameter this refers to the object that triggered the event itself, and KeyEventArgs contains the key information.

3, finally create a class of event receiver, this class first produces a delegate instance, and then adds this delegate instance to the event list that produces the event object, this process is called the subscription event. Then provide a method 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. KeyDown + = new Keyinputmonitor.keydownhandler (this. OnKeyDown);
}
private void OnKeyDown (object sender, KeyEventArgs e)
{
The Real event handler function
Console.WriteLine ("Capture key: {0}", E.keychar);
}
}


4, see how to call

public class Mainentrypoint
{
public static void Start ()
{
Instantiate an event sender
Keyinputmonitor monitor = new Keyinputmonitor ();
Instantiate an event sink
Eventreceiver eventreceiver = new Eventreceiver (monitor);
Run
Monitor. Run ();
}
}


Summarize:

Steps required for using events in C #:
1. Create a delegate
2. Associates the created delegate with a specific event (. NET class Library Many of the events are already custom-made, so they have a corresponding delegate, in writing the associated event handler-that is, when an event occurs when we want to execute the method we need to have the same signature as this delegate)
3. Write Event handlers
4. Generates a delegate instance using the written event handler
5. Add this delegate instance to the event list that produces the event object, which is called subscribing to Events

The process of generating and implementing events in C #:
1. Define a as an instance of the resulting event, A is an event generated by a
2. Define B as the instance that receives the event, B is the method for handling the event
3.A because the user (the program writer or program consumer) or the system generates an A event (for example, click a button to generate a click event)
4. A The event is notified by the delegate object in the event list to B
5.B to an event notification (actually B.B uses the delegate to implement the receiving of the event)
6. Call the B.b method to complete event handling
    public class A
    {
        public delegate void EventHandler (object Sender);
        public event EventHandler A;

        public void Run ()
        {
            Console.WriteLine ("Trigger an event.");
            A (this);
       }
   }

Class B
{
Public B (A a)
{
A.A + = new A.eventhandler (this.b);
}
private void B (object sender)
{
Console.WriteLine ("Received and handled an event.");
Console.read ();
}
}
The wrong place, welcome to correct me.
Finish

C # Event parsing

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.