1
using System;
2
using System.ComponentModel;
3
using System.Windows.Forms;
4
5
namespace WindowsFormsApplication1
6
{
7
public partial class Form1 : Form
8
{
9
public delegate void ActionEventHandler(object sender, ActionCancelEventArgs ev);//声明一个delegate
10
public static event ActionEventHandler Action;//声明一个名为Action的事件
11
12
string _time = "";
13
14
public Form1()
15
{
16
InitializeComponent();
17
Form1.Action += new ActionEventHandler(Form1_Action);//为事件Action增加处理程序(即通过ActionEventHandler这个delegate来调用Form1_Action)
18
}
19
20
private void Form1_Action(object sender, ActionCancelEventArgs ev) //这里的方法签名必须与ActionEventHandler的声明签名相同
21
{
22
ev.Cancel = DoAction();//调用DoAction,根据当前时间是否超过30秒,决定是否取消事件(小于30秒取消,反之继续)
23
if (ev.Cancel)
24
{
25
ev.Message = "当前时间小于30秒,事件被取消"; //如果取消,设置ev的Message属性
26
}
27
}
28
29
/// <summary>
30
/// 判断当前时间是否超过30秒
31
/// </summary>
32
/// <returns>小于30秒,返回true,反之返回false</returns>
33
private bool DoAction()
34
{
35
bool retVal = false;
36
DateTime tm = DateTime.Now;
37
38
if (tm.Second < 30)
39
{
40
_time = "";
41
retVal = true;
42
}
43
else
44
{
45
_time = "事件被触发于 " + DateTime.Now.ToLongTimeString();
46
}
47
48
return retVal;
49
}
50
51
/// <summary>
52
/// 声明一个当前时间的属性
53
/// </summary>
54
public string TimeString
55
{
56
get { return _time; }
57
}
58
59
protected void OnAction(object sender, ActionCancelEventArgs ev)
60
{
61
if (Action!=null)//如果有人订阅了Action事件
62
{
63
Action(sender, ev);//则事件触发
64
}
65
}
66
67
/// <summary>
68
/// 通过按钮来激发事件
69
/// </summary>
70
/// <param name="sender"></param>
71
/// <param name="e"></param>
72
private void btnRaise_Click(object sender, EventArgs e)
73
{
74
ActionCancelEventArgs cancelEvent = new ActionCancelEventArgs();//生成一个ActionCancelEventArgs的实例
75
OnAction(this, cancelEvent);//激发事件
76
if (cancelEvent.Cancel)//如果事件被取消,则显示Message
77
{
78
lblInfo.Text = cancelEvent.Message;
79
}
80
else//反之显示当前时间
81
{
82
lblInfo.Text = this.TimeString;
83
}
84
}
85
}
86
87
public class ActionCancelEventArgs: CancelEventArgs
88
{
89
string _msg = "";
90
91
//定义一个Message属性
92
public string Message
93
{
94
get { return _msg; }
95
set { _msg = value;}
96
}
97
98
}
99
}
100

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100
