Listen to key press when the program is in the background

前端 未结 1 735
自闭症患者
自闭症患者 2020-11-30 15:37

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 vb

相关标签:
1条回答
  • 2020-11-30 16:41

    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
    

    EDIT:

    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.

    0 讨论(0)
提交回复
热议问题