C # What is the event?

Source: Internet
Author: User

2012-07-26

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 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, we 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. The delegate can be understood as a function pointer. The difference is that the delegate is object-oriented and type-safe. For more information about delegation, see my other Article C # delegation's personal understanding. Event we can program the event 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. Description: 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, this class is used to monitor the input of keyboard buttons and trigger an event: internal class KeyInputMonitor {// create a delegate. The return type is void. The two parameters are public delegate void KeyDown (object sender, keyEventArgs e); // associate the created delegate with a specific event. Here, the specific event is OnKeyDown public ev. Ent KeyDown OnKeyDown; 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: // The KeyEventArgs keyEventArgs = new KeyEventArgs (responseChar); // trigger event OnKeyDown (this, keyEventArgs); break ;}} while (! Finished) ;}}pay attention to OnKeyDown (this, KeyEventArgs); this is the statement that triggers the event and submits the event to the KeyDown delegate for processing, delegate the specified 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. onKeyDown + = new KeyInputMonitor. keyDown (this. echo);} private void Echo (object sender, KeyEventArgs e) {// real event processing function Console. writeLine ("Capture key: {0}", e. keyChar) ;}} 4. Let's see how to call public class MainEntryPoint {public static void Start () {// instantiate an event transmitter KeyInputMonitor monitor = new KeyInputMonitor (); // instantiate an event receiver eventcycler = new eventcycler (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. add the delegated instance to the event list that generates the event object. This process is also called the process of event generation and implementation in event C # subscription: 1. define A as the instance that generates the event, and a as an event generated by A. 2. define B as the instance for receiving events, and B as the method for processing events. 3. A because 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 B5. B of this event through the delegate object in the event list to receive an event notification (actually B. b. Use delegation to receive events.) 6. call B. method B completes event processing
References: http://www.cnblogs.com/michaelxu/archive/2008/04/02/1134217.html

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.