C#学习笔记-KeyDown、KeyPress、KeyUp事件以及KeyCode、KeyData、KeyValue、KeyChar属性

本来没打算单独写的,但是在自己弄测试小程序的时候,越写发现不清楚的东西越多,所以实践又一次证明:纸上得来终觉浅,绝知此事要躬行!

直接贴代码了:

 1         //发生顺序:KeyDown->KeyPress->KeyUp
 2         //所有的参数的各种信息都在Keys里自带=>自己查看
 3 
 4         //KeyCode、KeyData、KeyValue对于字母键只记录大写的值
 5         //没有KeyChar
 6         //必须先将KeyPreview的属性设置为true
 7         
 8         private void Form1_KeyDown(object sender, KeyEventArgs e)
 9         {
10             if (e.Alt && e.Control && e.KeyCode == Keys.F2) 
11             {
12                 MessageBox.Show("You press the Alt and Ctrl and F2 buttons!");
13             }
14             if (e.KeyData == Keys.Up) 
15             {
16                 MessageBox.Show("You press the Up buttons!");
17             }
18             if (e.KeyValue == 27) 
19             {
20                 MessageBox.Show("You press the Esc buttons!");
21             }
22             
23         }
24 
25         //只能返回一个字符的ASCII码
26         //不能处理功能键、编辑键、组合键
27         //KeyChar能区分大小写
28         //KeyChar字存在于KeyPress中
29         private void Form1_KeyPress(object sender, KeyPressEventArgs e)
30         {
31             if (e.KeyChar == 65)
32             {
33                 MessageBox.Show("You press the A buttons!");
34             }
35             if (e.KeyChar == 97)
36             {
37                 MessageBox.Show("You press the a buttons!");
38             }
39             //KeyChar是不区分数字是否在大小哪个键盘的
40             if (e.KeyChar == 48)
41             {
42                 MessageBox.Show("You press the 0 buttons!");
43             }
44         }
45 
46 
47         //没有KeyChar
48         private void Form1_KeyUp(object sender, KeyEventArgs e)
49         {
50             //与KeyDown相似
51             //小键盘的数字0
52             if (e.KeyValue == 96)
53             {
54                 MessageBox.Show("You press the 0 buttons in keypad!");
55             }
56             //小键盘的数字0
57             if (e.KeyCode == Keys.NumPad0)
58             {
59                 MessageBox.Show("You press the 0 buttons in keypad!");
60             }
61             //主键盘的数字0
62             if (e.KeyCode == Keys.D0)
63             {
64                 MessageBox.Show("You press the 0 buttons in primary keyboard!");
65             }
66 
67         }

 另外:祝大家国庆节快乐!我也要去参加一起长大的哥哥的婚礼了啊......时间啊,就是这么匆匆溜走不回头的.......

原文地址:https://www.cnblogs.com/Aries-rong/p/5923529.html