在消息到达控件之前,Windows 窗体提供在窗体级别处理键盘消息的功能。 本文介绍如何完成此任务。
处理键盘消息
处理活动窗体的 KeyPress 或 KeyDown 事件,并将窗体的 KeyPreview 属性设置为 true
。 此属性使键盘输入在被窗体上的任何控件处理之前由窗体接收。 下面的代码示例通过检测所有数字键并使用 1、4 和 7 来处理KeyPress事件。
// Detect all numeric characters at the form level and consume 1,4, and 7.
// Form.KeyPreview must be set to true for this event handler to be called.
void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar >= 48 && e.KeyChar <= 57)
{
MessageBox.Show($"Form.KeyPress: '{e.KeyChar}' pressed.");
switch (e.KeyChar)
{
case (char)49:
case (char)52:
case (char)55:
MessageBox.Show($"Form.KeyPress: '{e.KeyChar}' consumed.");
e.Handled = true;
break;
}
}
}
' Detect all numeric characters at the form level and consume 1,4, and 7.
' Form.KeyPreview must be set to true for this event handler to be called.
Private Sub Form1_KeyPress(sender As Object, e As KeyPressEventArgs)
If e.KeyChar >= Chr(48) And e.KeyChar <= Chr(57) Then
MessageBox.Show($"Form.KeyPress: '{e.KeyChar}' pressed.")
Select Case e.KeyChar
Case Chr(49), Chr(52), Chr(55)
MessageBox.Show($"Form.KeyPress: '{e.KeyChar}' consumed.")
e.Handled = True
End Select
End If
End Sub