Reputation: 1194
I want to allow my application to do things like hit the enter key or type words without actually touching the keys. Is this possible? How could I make an onscreen keyboard that lets you type into different applications?
Upvotes: 1
Views: 1123
Reputation: 138051
The question about "how to create an onscreen keyboard" is very broad as there are many valid approaches to this, not one single and canonical way to do it. Therefore, you probably won't get much help about the high-level details of this task unless you can narrow down specific issues.
However, as far as keyboard events are concerned, you would use the Quartz Event Services API to fabricate keyboard events. Specifically, you are looking for CGEventCreateKeyboardEvent
and CGEventPost
.
// CGEvent functions
#import <ApplicationServices/ApplicationServices.h>
// kVK_* values
#import <Carbon/Carbon.h>
// press and release "abcd"
int virtualKeys[] = { kVK_ANSI_A, kVK_ANSI_B, kVK_ANSI_C, kVK_ANSI_D };
for (int i = 0; i < 4; i++)
{
// press the letter
CGEventRef event = CGEventCreateKeyboardEvent(NULL, virtualKeys[i], YES);
CGEventPost(kCGHIDEventTap, event);
CFRelease(event);
// wait .1 seconds
usleep(100000);
// release the letter
event = CGEventCreateKeyboardEvent(NULL, virtualKeys[i], NO);
CGEventPost(kCGHIDEventTap, event);
CFRelease(event);
}
For capitals, you need to "press" kVK_Shift
before the letter (and you need to release it as well).
Upvotes: 3