《编程的奥秘》读书笔记——读取按键
时间:2011-04-29 来源:水光
用户按下特定的按键,有三个事件可以读取按键,KeyPress、KeyDown、KeyUp。当用户按下并松开一个键时,三个事件的发生顺序:KeyDown、KeyPress、KeyUp。
e.Control = True And e.KeyCode = Keys.C ;用户同时按下了ctrl键和C键。
如果想在窗体级别处理键盘事件,比如textbox控件只接收数字,应在KeyPress事件中将KeyPressEventArgs.Handled 属性设置为 true。
示例代码: If Not Char.IsDigit(e.KeyChar) Then
e.Handled = True
End If
MSDN提供的方法:
' Boolean flag used to determine when a character other than a number is entered.
Private nonNumberEntered As Boolean = False
' Handle the KeyDown event to determine the type of character entered into the control.
Private Sub textBox1_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) _
Handles textBox1.KeyDown
' Initialize the flag to false.
nonNumberEntered = False
' Determine whether the keystroke is a number from the top of the keyboard.
If e.KeyCode < Keys.D0 OrElse e.KeyCode > Keys.D9 Then
' Determine whether the keystroke is a number from the keypad.
If e.KeyCode < Keys.NumPad0 OrElse e.KeyCode > Keys.NumPad9 Then
' Determine whether the keystroke is a backspace.
If e.KeyCode <> Keys.Back Then
' A non-numerical keystroke was pressed.
' Set the flag to true and evaluate in KeyPress event.
nonNumberEntered = True
End If
End If
End If
'If shift key was pressed, it's not a number.
If Control.ModifierKeys = Keys.Shift Then
nonNumberEntered = true
End If
End Sub 'textBox1_KeyDown
' This event occurs after the KeyDown event and can be used
' to prevent characters from entering the control.
Private Sub textBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) _
Handles textBox1.KeyPress
' Check for the flag being set in the KeyDown event.
If nonNumberEntered = True Then
' Stop the character from being entered into the control since it is non-numerical.
e.Handled = True
End If
End Sub 'textBox1_KeyPress
首先在KeyDown事件中检测键值是否是数字和退格键,如果不是,将变量nonNumberEntered标记为True,其次在KeyPress事件中根据变量值决定是否处理键盘事件。