Capture function keys F1..F12 in VB.NET

I cannot lock function keys F1.. F12for my application. I can fix the usual keys and modifiers such as shift, ctrl, alt, etc.

This question recommends KeyPreview = True, however, this does not 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
+3
source share
2 answers

Your code works for me, except that you have a typo in the EventHandler declaration. Change:

AddHandler Me.KeyDown, AddressOf KeyDownsHandler

to

AddHandler Me.KeyDown, AddressOf KeyDownHandler

alt text

+1
source

To capture keys (including function keys), I started using this template, which works quite well:

    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, , . , , , .

+3

Source: https://habr.com/ru/post/1784188/


All Articles