Listen to key press when the program is in the background

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 KeyDownBit As Integer = &H8000

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


To make the code only execute one time per key press, you can add a little While-loop to run until either of the buttons are released (add it inside your If-statement):

While GetAsyncKeyState(Keys.LWin) AndAlso GetAsyncKeyState(Keys.O)
End While

This will stop your code from executing more than once while you hold the keys down.

When using this in a Console Application just replace every System.Windows.Forms.Keys and Keys with ConsoleKey, and replace LWin with LeftWindows.

Leave a Comment