Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send Key Strokes to Games using Direct Input

Tags:

c#

I can send any windows application key strokes with PostMessage api. But I can't send key strokes to Game window by using PostMessage.

Anyone know anything about using Direct Input functions for sending keys to games from C#.

like image 508
Ibrahim AKGUN Avatar asked Jan 03 '09 21:01

Ibrahim AKGUN


2 Answers

An alternate way would be to hook the DirectInput API directly - Microsoft Research has provided a library to do this already: http://research.microsoft.com/en-us/projects/detours/

Once you hook into the API, you can do whatever you want with it. However, it's worth noting that in recent versions of Windows, DirectInput for mouse & keyboard input is just a wrapper around the Win32 windows messages. DirectInput spawns a thread in the background and simply intercepts window messages before passing them along back to the application. It's one of the reasons why Microsoft no longer recommends the use of DirectInput - and it means that messaging APIs like PostMessage should work just fine.

like image 165
Adrian Avatar answered Sep 19 '22 20:09

Adrian


One alternative, instead of hooking into DirectX, is to use a keyboard driver (this is not SendInput()) to simulate key presses - and event mouse presses.

You can use Oblita's Interception keyboard driver (for Windows 2000 - Windows 7) and the C# library Interception (wraps the keyboard driver to be used in C#).

With it, you can do cool stuff like:

input.MoveMouseTo(5, 5);
input.MoveMouseBy(25, 25);
input.SendLeftClick();

input.KeyDelay = 1; // See below for explanation; not necessary in non-game apps
input.SendKeys(Keys.Enter);  // Presses the ENTER key down and then up (this constitutes a key press)

// Or you can do the same thing above using these two lines of code
input.SendKeys(Keys.Enter, KeyState.Down);
Thread.Sleep(1); // For use in games, be sure to sleep the thread so the game can capture all events. A lagging game cannot process input quickly, and you so you may have to adjust this to as much as 40 millisecond delay. Outside of a game, a delay of even 0 milliseconds can work (instant key presses).
input.SendKeys(Keys.Enter, KeyState.Up);

input.SendText("hello, I am typing!");

/* All these following characters / numbers / symbols work */
input.SendText("abcdefghijklmnopqrstuvwxyz");
input.SendText("1234567890");
input.SendText("!@#$%^&*()");
input.SendText("[]\\;',./");
input.SendText("{}|:\"<>?");

Because the mechanism behind these key presses is a keyboard driver, it's pretty much unrestricted.

like image 33
Jason Avatar answered Sep 20 '22 20:09

Jason