SRL Archive - C/C++ Help and Tutorials

Simulate keyboard


JPHamlett

2009-11-08 13:42:36

Is there a way to simulate a keystoke through C++?

fronty

2009-11-08 14:35:21

Not in standard C++. Which platform are you using?

JPHamlett

2009-11-08 14:37:56

Dev-C++

fronty

2009-11-08 17:15:29

I meant operating system, but that tells enough.

First functions that pop to my mind are SendInput and SendMessage. Check MSDN for info.

You should throw Dev-C++ away. Now. It hasn't been updated in years, last commit was made in 20.8.2005. Get something which is more up to date.

Wizzup?

2009-11-08 17:17:34

Depends if you use Linux, Window$ or Mac.

On Windows, try SendMessage/SendInput.

Dan Cardin

2009-11-08 17:45:53

is there a crosser platform way?

Wizzup?

2009-11-08 18:25:56

From: Dan Cardin
is there a crosser platform way?


No. Not unless you write one yourself.

boberman

2009-11-10 13:42:25

From: Dan Cardin
is there a crosser platform way?

I can't remember, but I believe I put it into scar++ (I may not have put it in yet).

There is no universal way to send keys. It is very much OS dependent.

moose_are_fun

2009-11-12 13:47:09

Here's some functions that supports OS X (this isn't C++, it's just C, but it should work just the same):


#if defined(__APPLE__) && defined(__MACH__)
#define MACOSX 1
#else
#error "I said this only supports OS X!"
#endif

#include <assert.h> // For assert()
#include <ApplicationServices/ApplicationServices.h> // OSX-only header

void toggleKey(UniChar c, const bool down)
{
CGEventRef keyEvent = CGEventCreateKeyboardEvent(NULL, 0, down);
assert(keyEvent != NULL);

CGEventSetFlags(keyEvent, 0);
CGEventKeyboardSetUnicodeString(keyEvent, 1, &c);

CGEventPost(kCGSessionEventTap, keyEvent);
CFRelease(keyEvent);
}

inline void tapKey(UniChar c)
{
toggleKey(c, true);
toggleKey(c, false);
}

inline void typeString(CFStringRef str)
{
unsigned i, len = CFStringGetLength(str);
for (i = 0; i < len; ++i) {
tapKey(CFStringGetCharacterAtIndex(str, i));
}
}

For other platforms, take a look at the "SendKeys" function under Keyboard.cpp in Scar++.