Talking about the implementation of Winform events and the implementation of simulating their events, talking about the implementation of winform events

Source: Internet
Author: User

Talking about the implementation of Winform events and the implementation of simulating their events, talking about the implementation of winform events

When we are new to Winform, we are attracted by its magical event functions. When we click a button, we will jump to the clicking method we wrote. However, this does not conform to our understanding of the method. What does. net help us achieve in the future. How can we simulate the implementation of its events. Next, let's start with the Click method of the Button.

1. First, check the code automatically generated by the designer.


Partial class Form1 {# code generated by region Windows Form Designer // <summary> // The designer supports the required methods-do not // use the code editor to modify this method content. /// </Summary> private void InitializeComponent () {// instantiate a button this. button1 = new System. windows. forms. button (); this. suspendLayout (); // button1 // this. button1.Location = new System. drawing. points (491,100); this. button1.Name = "button1"; this. button1.Size = new System. drawing. size (75, 23); this. button1.TabIndex = 0; this. button1.Text = "button1"; this. button1.UseVisualStyleBackColor = true; // Add a click event this. button1.Click + = new System. eventHandler (this. button1_Click) ;}# endregion private System. windows. forms. button button1 ;}


We found that adding this. button1.Click + = new System. EventHandler (this. button#click) to the event );

This. What is the Click in button1.Click? Let's take a look at the definition of F12 (Note: The Button inherits from Control (all Control parent classes ))

We found that the event, Click is an event, and then let's look at the decompilation (we can see the implementation of + =,-=)

EventHandler is transferred to the sender event source (who triggered the event), e (event data)

So far this. button1.Click has added an event, but we know the event. button1 has subscribed to this event, but how has the event been triggered? We conduct debugging and observe in the call stack,

We perform reverse analysis from top to bottom
01.System. Windows. Forms. dll! System. Windows. Forms. Control. OnClick (System. EventArgs e) + 0x62Bytes.
System. Windows. Forms. Control. OnClickDecompilation. If handler is not empty, the event is subscribed and executed.
Private void button#click (object sender, EventArgs e ){}

02System. Windows. Forms. dll! System. Windows. Forms. Button. OnClick (System. EventArgs e) + 0x80 bytes
System. Windows. Forms. Button. OnClickDecompile and call the 01 method.

03System. Windows. Forms. dll! System. Windows. Forms. Button. OnMouseUp (System. Windows. Forms. MouseEventArgs
Mevent = {X = 36 Y = 13 Button = Left}) + 0xac bytes,WeSystem. Windows. Forms. Button. OnMouseUpDecompile,
The method finally calls the Control. OnMouseUp method to execute the mouse-up event.

04System. Windows. Forms. dll! System. Windows. Forms. Control. WmMouseUp (ref System. Windows. Forms. Message m, System. Windows. Forms. MouseButtons button, int clicks) + 0x274 bytesWeSystem. Windows. Forms. Control. WmMouseUp DecompilationThis is the determination of the mouse event, we will be surprised to find that there is a judgment on the click and double-click.


When you go down, you are listening to mouse events. If you are interested, you can continue to view the call stack,


To sum up, the trigger process of the button's click is as follows:

So far, we have some knowledge about Winform events. How can we use this idea to handle our own events?

Next, we simulate a scenario where we have a text file that we listen to. If the text file changes (equivalent to the mouse monitoring trigger event mentioned above ), the trigger event sends a message to the Administrator and the user (the person here is equivalent to the button object, simulating the click event of different Winform controls to different people ). Use the Winform event technology;

1 first define the delegate of an event


// The delegate declaration after the file is changed: public delegate void MonitorEventHandler (object sender, EventArgs e );


2. event data transmitted by the event

// The event data class inherits from EventArgs public class MsgEventArgs: eventArgs {// <summary> ///// </summary> /// <param name = "changeTime"> modification time </param> /// <param name = "toSend"> message </param> public MsgEventArgs (DateTime changeTime, string toSend) {this. changeTime = changeTime; this. toSend = toSend;} // modification time public DateTime ChangeTime {get; set ;}// message public string ToSend {get; set ;}}

3 MonitorText monitoring File class (equivalent to the mouse monitoring class mentioned above)

Public class MonitorText {// defines the monitoring text event public event MonitorEventHandler MonitorEvent; // the last File update time is used to determine whether the File has modified private DateTime _ lastWriteTime = File. getLastWriteTime (@ "C: \ Users \ HHY \ Desktop \ 1.txt"); public MonitorText () {}// file update call protected virtual void OnTextChange (MsgEventArgs e) {if (MonitorEvent! = Null) {// It is not null. The method used to process event MonitorEvent (this, e) ;}// public void BeginMonitor () {DateTime bCurrentTime; while (true) {bCurrentTime = File. getLastWriteTime (@ "C: \ Users \ HHY \ Desktop \ 1.txt"); if (bCurrentTime! = _ LastWriteTime) {_ lastWriteTime = bCurrentTime; MsgEventArgs msg = new MsgEventArgs (bCurrentTime, "Text changed"); OnTextChange (msg );}
// Monitor Thread. Sleep (0.1) every 100 seconds );}}}

4. Administrator class (relative to the Button class)

Public class Administrator {// Administrator event handling method public void OnTextChange (object Sender, EventArgs e) {Console. writeLine ("Dear administrator:" + DateTime. now. toString () + ": file changed. ");}}

5. User class (compared with the control class other than the Button class)

Public class User {// User event handling method public void OnTextChange (object Sender, EventArgs e) {Console. writeLine ("Dear User:" + DateTime. now. toString () + ": file changed. ");}}

6. Main method of the program

Class Program {// defines the monitoring Text object static MonitorText MonitorTextEventSource; static void Main (string [] args) {MonitorTextEventSource = new MonitorText (); // 1. start the background Thread to add the monitoring event var thrd = new Thread (MonitorTextEventSource. beginMonitor); thrd. isBackground = true; thrd. start (); // 2 instantiate the Administrator class Administrator ad = new Administrator (); // 3 instantiate the User class user User = new User (); // 4 subscribe to the event MonitorTextEventSource. monitorEvent + = ad. onTextChange; MonitorTextEventSource. monitorEvent + = user. onTextChange; Console. readLine ();}}

Run the program

Now, our simulation is complete, and the Winform event process is basically implemented again. Please point it out because we are also a little bit unintelligible, I put the program source code below, you can debug and run it.

Source Code address:


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: 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.