如何处理窗体中的键盘输入消息(Windows 窗体 .NET)

Windows 窗体能够在消息到达控件之前处理窗体级别的键盘消息。 本文演示如何完成此任务。

处理键盘消息

处理有效窗体的 KeyPressKeyDown 事件,并将该窗体的 KeyPreview 属性设置为 true。 此属性会使键盘消息在到达窗体上的任何控件之前就被窗体接收。 以下代码示例通过检测所有数字键并使用 147 来处理 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

另请参阅