




















对教材3.2.2部分进行演示,该例题包括自定义控件事件的代码
1
using System;
2
3
namespace override_attribute_event
4
{
5
6
public class NumericTextBox : System.Windows.Forms.TextBox
7
{
8
public NumericTextBox()
9
{
10
//
11
// TODO: 在此处添加构造函数逻辑
12
//
13
}
14
15
//重载TextBox的Text属性
16
public override string Text
17
{
18
get
19
{
20
return base.Text;
21
}
22
set
23
{
24
try
25
{
26
int.Parse(value);
27
base.Text = value;
28
return;
29
}
30
catch
31
{
32
//如果输入文本部为数值,则不作任何操作
33
}
34
//输入文本为空的时候也可行
35
if (value == null)
36
{
37
base.Text = value;
38
return;
39
}
40
}
41
}
42
43
//重载了TextBox的OnKeyPress事件,不让用户点击数字键和Backspace键以外的键
44
protected override void OnKeyPress(System.Windows.Forms.KeyPressEventArgs e)
45
{
46
//判断用户的按键
47
int asciiInteger = Convert.ToInt32(e.KeyChar);
48
if (asciiInteger >= 47 && asciiInteger <= 57)
49
{
50
e.Handled = false;//将TextBox自身的OnKeyPress触发,实现了数字键的文本输入
51
return;
52
}
53
if (asciiInteger == 8)
54
{
55
e.Handled = false;
56
return;
57
}
58
e.Handled = true;
59
//如果用户点击了非数字键,则调用自定义的事件InvalidUserEntry
60
if (InvalidUserEntry != null)
61
{
62
InvalidUserEntry(this,e);
63
}
64
}
65
66
//自定义事件
67
public delegate void MyEvent(object sender,System.Windows.Forms.KeyPressEventArgs e);
68
69
public event MyEvent InvalidUserEntry;
70
71
72
73
}
74
}
75
完整源代码下载:override_attribute_event.rar
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。