VB Simulate keystrokes via user32

473 views Asked by At

I want to simulate keystrokes like I did with mouse clicks and I happened to find some example code online.

Declaration

Public Const MOUSEEVENTF_LEFTDOWN = &H2
Public Const MOUSEEVENTF_LEFTUP = &H4

Declare Function apimouse_event Lib "user32.dll" Alias "mouse_event" (ByVal dwFlags As Int32, ByVal dX As Int32, ByVal dY As Int32, ByVal cButtons As Int32, ByVal dwExtraInfo As Int32) As Boolean

Simulating MouseClicks

Call apimouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
Call apimouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)

The above code can simulate mouse clicks even in directx application. Is there a similar way to simulate keystrokes as well? It would also be great if you can explain what the above code does since I don't quite understand it.

1

There are 1 answers

2
Justin Ryan On BEST ANSWER

Naturally, instead of using "mouse event" messages, you would use "keyboard events." Have a look at the keybd_event page at pinvoke.net for some examples.

Keep in mind, these literally emulate a user hitting keys on the keyboard, so they are always sent to the control with focus ('foreground'). If you need to send specific keystrokes to hidden, or background windows, what you're looking for are the SendMessage related functions.