The event processing mechanism is not very clear all the time. Today, after reading the article 'C # event parsing after the storm, the idea is much clearer after imitating a piece of code. below is the code:
1 using system;
2 using system. Collections. Generic;
3 using system. text;
4
5 namespace t_event
6 {
7 class Program
8 {
9 static void main (string [] ARGs)
10 {
11 keyinputmonitor monitor = new keyinputmonitor ();
12
13 eventreceive receive = new eventreceive (MONITOR );
14
15 monitor. Run ();
16}
17}
18
19 // This class is used to save the key information
// Internal modifier: the type or member declared with this modifier can only access interface members in the same set
20 internal class keyeventarg: eventargs
21 {
22 private char keychar;
23
24 public keyeventarg (char keychar)
25 {
26 This. keychar = keychar;
27}
28
29 public char keychar
30 {
31 get
32 {
33 return keychar;
34}
35}
36}
37
38 internal class keyinputmonitor
39 {
40 public delegate void keydownhandle (Object sender, keyeventarg E );
41
42 public event keydownhandle onkeydownhandle;
43
44 public void run ()
45 {
46 bool flag = false;
47 do
48 {
49 console. writeline ("Please input a char ");
50 string response = console. Readline ();
51 char rchar = (response = "")? '': Char. toupper (response [0]);
52 switch (rchar)
53 {
54 case 'X ':
55 flag = true;
56 break;
57 default:
58 // instantiate a keyeventarg to obtain the key information
59 keyeventarg = new keyeventarg (rchar );
60 // trigger the onkeydownhandle event and handle it in the method specified by the delegate keydownhandle
61 onkeydownhandle (this, keyeventarg );
62 break;
63}
64} while (! Flag );
65}
66}
67
68 internal class eventreceive
69 {
70 public eventreceive (keyinputmonitor Monitor)
71 {
72 // subscribe to events after the program starts, and add the delegated instance to the event list that generates event objects
73 monitor. onkeydownhandle + = new keyinputmonitor. keydownhandle (this. Echo );
74}
75
76 private void echo (Object sender, keyeventarg E)
77 {
78 console. writeline ("capture key: {0}", E. keychar );
79 // check the value passed by sender (this). It turns out to be the keyinputmonitor class.
80 string strsender = sender. tostring ();
81 console. writeline (strsender );
82}
83}
84}
Comments are written according to your own understanding. If the comments are incorrect, correct them.