0

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.

Perplex
  • 11
  • 6
  • Go to codeproject.com and search for _Global Mouse and Keyboard Library_. The first hit should be a project by Brian Geiman. That project implements both the mouse and keyboard apis you need and has a simple demo project that records and plays back mouse and keyboard events. – Chris Dunaway Jun 09 '15 at 20:12
  • As much as I understand the C# syntax, I struggle to implement the same code into my VB.net project. Also I am looking for a simpler alternative instead of creating multiple classes just for this functionality. – Perplex Jun 09 '15 at 20:27

1 Answers1

0

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.

Justin Ryan
  • 1,409
  • 1
  • 12
  • 25
  • Thanks, I got it to work on notepad but not on directx. Maybe it's something else that I'm looking for – Perplex Jun 09 '15 at 20:35
  • Without knowing details about the application, or your project, my guess would be that the DirectX app does not have focus, or loses focus at some point. The `SendMessage` functions I mentioned allow you to target specific message loops by window handle, so you are guaranteed to be sending messages to the correct target. `SendMessage` is somewhat more complex to use, but there exist considerable [examples](http://stackoverflow.com/questions/5641869/sending-an-application-keystrokes-with-sendmessage-vb-net). – Justin Ryan Jun 09 '15 at 20:45