在VB.NET中捕获功能键F1..F12

时间:2011-01-07 22:21:19

标签: .net vb.net winforms .net-2.0 keypress

我无法为我的应用程序捕获功能键 F1 .. F12 。我能够捕获常规键和修饰符,例如 shift ctrl alt 等。

question建议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

2 个答案:

答案 0 :(得分:4)

为了捕获键(包括功能键)我已经开始使用这种模式,这非常有效:

    Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, ByVal keyData As System.Windows.Forms.Keys) As Boolean
        Select Case keyData
            Case Keys.F2
                ' Do something 

            Case Keys.F3
                ' Do more

            Case Keys.Escape
                ' Crap

            Case Else
                Return MyBase.ProcessCmdKey(msg, keyData)

        End Select

        Return True
    End Function

这将自动禁止您在Select语句中处理的每个键。如果你想使用Shift,Alt或Ctrl组合,你只需要Or。当然,这适用于非常低的Form级别,这使其独立于您在该表单上的任何控件。如果您不知道这一点,它也会触发奇怪的行为,例如焦点跳跃或行为不当的控件。

答案 1 :(得分:1)

您的代码适用于我,但您的EventHandler声明中有拼写错误。变化:

AddHandler Me.KeyDown, AddressOf KeyDownsHandler

AddHandler Me.KeyDown, AddressOf KeyDownHandler

alt text