本來沒打算單獨寫的,但是在自己弄測試小程序的時候,越寫發現不清楚的東西越多,所以實踐又一次證明:紙上得來終覺淺,絕知此事要躬行!
直接貼代碼了:
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 }
另外:祝大家國慶節快樂!我也要去參加一起長大的哥哥的婚禮了啊......時間啊,就是這麼匆匆溜走不回頭的.......