Richard Olsen Sandberg Richard Olsen Sandberg - 6 months ago 36 Question

Listen to key press when the program is in the background process

I am currently working with a program which is supposed to run in the background but also check if "mod + o" is pressed then do something. But I cannot figure out how a program can listen to key presses when the program is not Selected / Opened.


You can use P/Invocation to be able to use WinAPI's GetAsyncKeyState() function, then check that in a timer.

<DllImport("user32.dll")> _
Public Shared Function GetAsyncKeyState(ByVal vKey As System.Windows.Forms.Keys) As Short
End Function

Const KeyDown As Short = &H8000

Private Sub Timer1_Tick(sender As Object, e As System.EventArgs) Handles Timer1.Tick
    If (GetAsyncKeyState(Keys.O) And KeyDown) = KeyDown Then
        'Do whatever you want when 'O' is held down.
    End If
End Sub

I cannot seem to find what the Mod key is, so you can do this in your form (when it has focus):

Private Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Form1.KeyDown
End Sub

Press the 'Mod' button ONLY, then take the number from the message box that popups and put it in the timer:

If (GetAsyncKeyState(<put number here>) And KeyDown) = KeyDown AndAlso (GetAsyncKeyState(Keys.O) And KeyDown) = KeyDown Then
        'Do whatever you want when 'Mod + O' is held down.
End If