如何 simulate/release 键盘按键?

How do I simulate/release keyboard keys?

我需要一种在满足特定条件时模拟键盘按键的方法,我还需要知道当前按下的是模拟键还是真实键。这需要在主应用程序之外工作。

这就是我需要它的工作方式:

    Dim UserDefinedKey As Keys = Keys.H
    Do
        If GetAsyncKeyState(UserDefinedKey) Then
            Thread.Sleep(30)
            'release the set key
            Thread.Sleep(30)
            'press/hold the set key once, continue the loop if the real key is still been held.
        End If
    Loop While GetAsyncKeyState(UserDefinedKey) '/ loop while real key is being held
    'Real key is no longer held, release the simulated key press.

如有任何帮助,我们将不胜感激。 (这段代码是为了在游戏中自动执行某些事情,这就是为什么它需要在主应用程序之外工作)

我有一些东西允许用户设置他们自己的键,这只是我需要的一个小例子,它只是我坚持使用的键盘模拟部分,并确定是否是真正的键还压不压

你需要 Windows API 钩子(初学者不需要),或者像 MouseKeyHook

这样的第三方库

抱歉让您久等了...通过 Window Messages 模拟键盘输入结果 复杂得多 与用同样的方式模拟鼠标输入相比

无论如何,我终于完成了所以这里有一个 complete InputHelper class 用于模拟两者通过鼠标和键盘输入流或通过Window Messages.

虚拟地进行鼠标和键盘输入

下载地址GitHub: https://github.com/Visual-Vincent/InputHelper/releases
(源码太长贴在答案里)

Dim UserDefinedKey As Keys = Keys.H

'Using a regular While-loop is better since you won't need your If-statement then.
While InputHelper.Keyboard.IsKeyDown(UserDefinedKey)
    Dim ActiveWindow As IntPtr = InputHelper.WindowMessages.GetActiveWindow()
    Thread.Sleep(30)
    InputHelper.WindowMessages.SendKey(ActiveWindow, UserDefinedKey, False) 'False = Key up.
    Thread.Sleep(30)
    InputHelper.WindowMessages.SendKey(ActiveWindow, UserDefinedKey, True) 'True = Key down.
End While

关于 InputHelper 的子 class 的一些信息:

InputHelper.Keyboard

  • 处理和模拟物理键盘输入的方法(即GetAsyncKeyState()检测输入)。​​

InputHelper.Mouse

  • 处理和模拟物理鼠标输入的方法。

InputHelper.WindowMessages

  • 处理和模拟虚拟键盘和鼠标输入的方法(即未被GetAsyncKeyState()检测到的输入)。

希望对您有所帮助!