How do I simulate/release keyboard keys?

放肆的年华 提交于 2019-12-14 03:26:51

问题


I need a way to simulate keyboard keys if a certain condition is met, I also need to know if it's the simulated key that's currently pressed or the real key. This needs to work outside the main application.

This is how I would need it to work:

    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.

Any help would be greatly appreciated. (This code is to automate certain things inside of a game which is why it needs to work outside the main application)

I have certain things in place to allow the user to set their own key, this was just a small example of what I need, it's just the keyboard simulating part i'm stuck with and determining if the real key is still pressed or not.


回答1:


So sorry for the long wait... Simulating keyboard input via Window Messages turned out to be far much more complicated compared to simulating mouse input in the same way.

Anyway, I am finally done with it so here's a complete InputHelper class for simulating both mouse and keyboard input virtually via the mouse and keyboard input stream or via Window Messages.

Download at GitHub: https://github.com/Visual-Vincent/InputHelper/releases
(source code is too long to be pasted in the answer)

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

A little information about InputHelper's sub-classes:

InputHelper.Keyboard

  • Methods for handling and simulating physical keyboard input (i.e. input detected by GetAsyncKeyState()).

InputHelper.Mouse

  • Methods for handling and simulating physical mouse input.

InputHelper.WindowMessages

  • Methods for handling and simulating virtual keyboard and mouse input (i.e. input that is not detected by GetAsyncKeyState()).

Hope this helps!




回答2:


You will need Windows API hooks for that (nothing for beginners), or third party library like MouseKeyHook



来源:https://stackoverflow.com/questions/45155757/how-do-i-simulate-release-keyboard-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!