如何處理表單中的鍵盤輸入訊息 (Windows Forms .NET)

在訊息到達控制項之前,Windows Form 提供在表單層級處理鍵盤訊息的能力。 本文說明如何完成這項工作。

重要

.NET 7 和 .NET 6 的桌面指南檔正在建置中。

處理鍵盤訊息

處理使用 KeyPress 中表單的 或 KeyDown 事件,並將表單的 屬性設定 KeyPreviewtrue 。 此屬性會在表單到達表單上的任何控制項之前,先收到表單的鍵盤。 下列程式碼範例會偵測所有數位索引鍵並取 用 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

另請參閱