C # event Parsing
Event is always mysterious and hard to understand for beginners. These things are often common and important in programming. As we all know, Windows message processing mechanism is important. In fact, C # events are based on Windows message processing mechanism, but encapsulation is better, so developers do not need to know the underlying message processing mechanism, you can develop powerful event-based applications.
Let's take a look at the benefits of event programming.
In the past, we often used a waiting mechanism to write such programs. To wait for something to happen, we need to constantly detect certain judgment variables. After the introduction of event programming, this process is greatly simplified:
-Using events, you can easily determine the program execution sequence.
-When the event driver waits for an event, it does not occupy a lot of resources. The biggest difference between an event driver and a procedural program is that the program does not constantly check the input device, but does not wait until the message arrives. Each input message is queued, wait for the program to process it. If no message is waiting, the program returns the control to the operating system to run other programs.
-Events simplify programming. The operating system simply transmits messages to the object, and the event driver of the object determines the event processing method. The operating system does not need to know the internal working mechanism of the program, but only needs to know how to communicate with objects, that is, how to transmit messages.
With so many benefits, it seems necessary for us to master it. As the saying goes: "it's hard, it's not hard ". Let's start step by step...
To talk about events, you must talk about delegation ). The relationship between them can be illustrated through a simple analogy, which may not be very appropriate. For example, if you want to rent a house, this is an event. Then, the entrusting agency is the house leasing agency. After you tell the intermediary about the house rental, an intermediary will produce a house rental plan that meets your requirements. Then, when the intermediary executes this plan, you rent the house, that is, the incident is handled. Of course, you can also look for the landlord directly without an intermediary, but if there is no Internet or other tools, how do you get information about who rented the house? The topic is far away.
Delegate)
Delegation can be understood as function pointers. The difference is that delegation is object-oriented and type-safe. For more information about delegation, see my other Article C # delegation's personal understanding.
Event)
We can simply divide event programming into two parts: the class of event occurrence (written called event generator) and the class of event receiving and processing. The class where the event occurs is that an event is triggered in this class, but this class does not know which object or method will receive and process the event triggered by it. It is necessary to have a media between the sender and receiver. This media is a delegate in. NET Framework ). In the class for receiving and processing events, we need to have a method for processing events. Well, we will implement a program to capture keyboard keys in this Order and explain how to write the event application step by step.
1. Create your own eventargs class.
Introduced from msdn:
Eventargs is the base class of the class that contains event data. This class is used for events that do not pass status information to the event handler when an event is triggered. If the event handler needs status information, the application must derive a class from this class to save data.
Because we need to include the key information in the keyboard button event, we need to derive a keyeventargs class to save the key information so that we can 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 another event class keyinputmonitor, which is used to monitor input of keyboard buttons and trigger an event:
Internal
Class keyinputmonitor
{
// Create a delegate with the return type void and two parameters
Public
Delegate void keydownhandler (
Object sender, keyeventargs E );
// Associate the created delegate with a specific event. The specific event here 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:
// Obtain the key information Parameters
Keyeventargs
= New keyeventargs (responsechar );
// Trigger the event
Keydown (
This, keyeventargs );
Break;
}
} While (
! Finished );
}
}
Here, pay attention to keydown (this, keyeventargs); this is the statement that triggers the event, and submit the event to the keydownhandler delegate for processing, and delegate the designated event processing method to process the event, this is the class of the event receiver. The parameter "this" refers to the object that triggers the event. The keyeventargs contains the key information.
3. Finally, create a class for the event receiver. This class first generates a delegate instance and then adds the delegate instance to the event list that generates the event object, this process is also called a subscription event. Then, a method is provided to display the key information.
Internal
Class eventreceiver
{
Public eventreceiver (keyinputmonitor Monitor)
{
// Generate a delegate instance and add it to the event list generated by keyinputmonitor
Monitor. keydown
+ = New keyinputmonitor. keydownhandler (
This. onkeydown );
}
Private
Void onkeydown (Object sender, keyeventargs E)
{
// Real event processing functions
Console. writeline (
"Capture key: {0}", E. keychar );
}
}
4. Let's see how to call
Public
Class mainentrypoint
{
Public
Static void start ()
{
// Instantiate an event sender
Keyinputmonitor Monitor
= New keyinputmonitor ();
// Instantiate an event Receiver
Eventreceiver
= New eventreceiver (MONITOR );
// Run
Monitor. Run ();
}
}
Summary:
Steps required to use the event in C:
1. Create a delegate
2. associate the created delegate with a specific event (. many events in the. NET Class Library have been customized, so they have a corresponding delegate, when writing the associated Event Handler-that is, when an event occurs, we need to execute the method with the same signature as this delegate)
3. Write an event handler
4. Use the compiled event handler to generate a delegate instance
5. Add the delegated instance to the event list that generates the event object. This process is also called subscription event.
Process for event generation and implementation in C:
1. Define a as the instance that generates the event, and a as an event generated by
2. Define B as the instance for receiving events, and B as the method for handling events.
3. A a user (program writer or program user) or the system generates an A event (for example, clicking a button to generate a click event)
4. A notifies B of this event through the delegate object in the event list
5. B receives an event notification (B. B uses delegation to receive the event)
6. Call Method B to complete event processing.
Public Class
{
Public Delegate void eventhandler (Object sender );
Public event eventhandler;
Public void run ()
{
Console. writeline ("trigger an event .");
A (this );
}
}
Class B
{
Public B ()
{
A. A + = new A. eventhandler (this. B );
}
Private void B (Object sender)
{
Console. writeline ("received and handled an event .");
Console. Read ();
}
}
Correction is not recommended.
(End)