How to listen keyboard in background and fire keystrokes on demand?

后端 未结 2 1954
南旧
南旧 2020-11-29 10:58

I want to make a program in vb.NET 2008 which will listen keyboard in background, i.e. even though the application is minimized (globally). If a specific key is been pressed

2条回答
  •  生来不讨喜
    2020-11-29 11:12

    If you use KeyboardHook class, make sure you have to build your program before using. With regards to the question for a specific key, you can trigger it in KeyDown or KeyUp event. But before that, you have to use sendkeys to send keys to active window.

    SendKeys.Send("L") 'Sends letter L to active window.

    Then you can do the following code; below checks if letter "a" is being pressed.

    Private Sub kbHook_KeyDown(ByVal Key As System.Windows.Forms.Keys) Handles kbHook.KeyDown
        Debug.WriteLine(Key.ToString) 
        if Key.ToString() = "a" then
         'trigger your sendkeys
        end if
    End Sub 
    

    To trigger a specific key like a switch button, just declare a boolean variable to check if the button is switched or not. You can declare it globally:

    Dim switch as boolean = false

    Just update the area where you set a condition to check the letter pressed. It will look like below:

    if Key.ToString() = "a" then
      if switch = false then
        switch = true
        'trigger send keys
      else
        switch = false
        'deactivate send keys
      end if
    end if
    

    To have a specific time in sending keys, use timer. I hope it helps.

提交回复
热议问题