如何处理窗体中的键盘输入消息(Windows 窗体 .NET)
Windows 窗体能够在消息到达控件之前处理窗体级别的键盘消息。 本文演示如何完成此任务。
重要
面向 .NET 7 和 .NET 6 的桌面指南文档正在撰写中。
处理键盘消息
处理有效窗体的 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
另请参阅
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈