Elsendion
Elsendion

Reputation: 187

C/C++ program to press key every X seconds

i've got some experience using C/C++ language. But i'm playing a game(independent software from mine), and i'd like to make a C program that interacts with the game, to press the key 2 or Space every two seconds. It's for windows.

Any ideas?

Upvotes: 0

Views: 1948

Answers (2)

Kirk Backus
Kirk Backus

Reputation: 4886

Have a look at the functions SendInput and keybd_event. Those are functions that will tell Windows to press a key.

And all you need to do is create a loop that sleeps every 2 seconds. keybd_event is the old convention, but it is the one I'm familiar with.

VOID WINAPI keybd_event(
  _In_  BYTE bVk,
  _In_  BYTE bScan,
  _In_  DWORD dwFlags,
  _In_  ULONG_PTR dwExtraInfo
);

The following will simulate the pressing of the NumLock

// Simulate a key press
keybd_event( VK_NUMLOCK, 0x45, KEYEVENTF_EXTENDEDKEY | 0, 0);

// Simulate a key release
keybd_event( VK_NUMLOCK, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);

Upvotes: 1

KrisSodroski
KrisSodroski

Reputation: 2852

In windows, this is pretty easy. Make a C++ console program. Inside your program, you'll need to search all the "windows" in Windows. Microsoft calls these windows window handles (HWND). You can search through them all with FindWindowEx: http://msdn.microsoft.com/en-us/library/windows/desktop/ms633500(v=vs.85).aspx. once you find your window (by name), you can send TO the window HWND keypresses. This is done with SendMessage(); Put this in a loop every 2 seconds and you're done!

You can find the window you're searching for's properties by using Visual Studio's Spy++. This will let you easily know what window name to search for.

Upvotes: 0

Related Questions