VB.NET中捕获功能键F1..F12
我无法捕获我的应用程序的功能键 F1..F12。我能够捕获常规键和修饰符,例如 shift、ctrl、alt 等。
这个 问题建议KeyPreview = True
,但这似乎不适用于我的应用程序。我做错了什么?
Private Sub Main_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.KeyPreview = True
AddHandler Me.KeyDown, AddressOf KeyDownsHandler
AddHandler Me.KeyUp, AddressOf KeyUpHandler
End Sub
Private Sub KeyUpHandler(ByVal o As Object, ByVal e As KeyEventArgs)
e.SuppressKeyPress = True
If e.KeyCode = Keys.F1 Then
txtMain.AppendText("F1 was pressed!" & Environment.NewLine)
End If
txtMain.AppendText( _
String.Format("'{0}' '{1}' '{2}' '{3}' {4}", e.Modifiers, e.KeyValue, e.KeyData, e.KeyCode, Environment.NewLine))
End Sub
Private Sub KeyDownHandler(ByVal o As Object, ByVal e As KeyEventArgs)
e.SuppressKeyPress = True
txtMain.AppendText( _
String.Format("'{0}' '{1}' '{2}' '{3}' {4}", e.Modifiers, e.KeyValue, e.KeyData, e.KeyCode, Environment.NewLine))
End Sub
I cannot capture the function keys F1..F12 for my application. I am able to capture regular keys and modifiers such as shift, ctrl, alt, etc..
This question recommends KeyPreview = True
, however that does not seem to work for my application. What am I doing wrong?
Private Sub Main_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.KeyPreview = True
AddHandler Me.KeyDown, AddressOf KeyDownsHandler
AddHandler Me.KeyUp, AddressOf KeyUpHandler
End Sub
Private Sub KeyUpHandler(ByVal o As Object, ByVal e As KeyEventArgs)
e.SuppressKeyPress = True
If e.KeyCode = Keys.F1 Then
txtMain.AppendText("F1 was pressed!" & Environment.NewLine)
End If
txtMain.AppendText( _
String.Format("'{0}' '{1}' '{2}' '{3}' {4}", e.Modifiers, e.KeyValue, e.KeyData, e.KeyCode, Environment.NewLine))
End Sub
Private Sub KeyDownHandler(ByVal o As Object, ByVal e As KeyEventArgs)
e.SuppressKeyPress = True
txtMain.AppendText( _
String.Format("'{0}' '{1}' '{2}' '{3}' {4}", e.Modifiers, e.KeyValue, e.KeyData, e.KeyCode, Environment.NewLine))
End Sub
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为了捕获按键(包括功能键),我开始使用这种模式,效果非常好:
这将自动抑制您在
Select
语句中处理的每个键。如果您想使用 Shift、Alt 或 Ctrl 的组合,则只需或
它们。当然,这适用于非常低的Form
级别,这使得它独立于该表单上的任何控件。如果您不知道,它也会触发奇怪的行为,例如焦点跳跃或行为不当的控件。For capturing keys (including function keys) I've started to use this pattern, which works quite well:
This will automatically suppress every key you handle in the
Select
statement. If you want to use combinations with Shift, Alt or Ctrl you'll just have toOr
them. Of course this works on a very lowForm
level which makes it independent from any Control you have on that form. It will also trigger weird behavior if you do not know that, like focus-jumps or badly behaving Controls.您的代码对我有用,但您的 EventHandler 声明中有一个拼写错误。更改:
至
Your code works for me with the exception that you have a typo in your EventHandler declaration. Change:
to