參考連結
https://docs.microsoft.com/zh-tw/dotnet/framework/winforms/how-to-handle-keyboard-input-at-the-form-level
主要部分
form的地方需要加入
public Form1()
{
this.KeyPreview = true;
this.KeyPress += new KeyPressEventHandler(Form1_KeyPress);
TextBox1.KeyPress += new KeyPressEventHandler(TextBox1_KeyPress);
}
建立鍵盤keyPress事件
void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar >= 48 && e.KeyChar <= 57)
{
MessageBox.Show("Form.KeyPress: '" +
e.KeyChar.ToString() + "' pressed.");
switch (e.KeyChar)//e.KeyChar 為你偵測到的鍵盤代碼
{
case (char)49:
case (char)52:
case (char)55:
MessageBox.Show("Form.KeyPress: '" +
e.KeyChar.ToString() + "' consumed.");
e.Handled = true;
break;
}
}
}
使用前記得先去看一下鍵號
http://web.tnu.edu.tw/me/study/moodle/tutor/vb6/tutor/r03/index.htm
字母
|
鍵碼值
|
字母
|
鍵碼值
|
其它鍵
|
鍵碼值
|
其它鍵
|
鍵碼值
|
A
|
65
|
N
|
78
|
Backspace
|
8
|
Left Arrow
|
37
|
B
|
66
|
O
|
79
|
Tab
|
9
|
Up Arrow
|
38
|
C
|
67
|
P
|
80
|
Clear
|
12
|
Right Arrow
|
39
|
D
|
68
|
Q
|
81
|
Enter
|
13
|
Down Arrow
|
40
|
E
|
69
|
R
|
82
|
Shift
|
16
|
Insert
|
45
|
F
|
70
|
S
|
83
|
Control
|
17
|
Delete
|
46
|
G
|
71
|
T
|
84
|
Alt
|
18
|
Help
|
47
|
H
|
72
|
U
|
85
|
Caps Lock
|
20
|
Num Lock
|
144
|
I
|
73
|
V
|
86
|
Esc
|
27
|
; :
|
186
|
J
|
74
|
W
|
87
|
Spacebar
|
32
|
= +
|
187
|
K
|
75
|
X
|
88
|
Page Up
|
33
|
- _
|
189
|
L
|
76
|
Y
|
89
|
Page Down
|
34
|
/ ?
|
191
|
M
|
77
|
Z
|
90
|
End
|
35
|
\Q ~
|
192
|
Home
|
36
|
[ {
|
219
|
||||
\ |
|
220
|
||||||
] }
|
221
|
沒有留言:
發佈留言