Cocoa Virtual Keystrokes Pain
- by bhargav
I'm writing an application to respond on a hotkey by copying highlighted text into NSPasteboard's generalPasteboard. After looking around here for a solution for sending virtual keystrokes, I found this: http://stackoverflow.com/questions/1505933/how-to-send-a-cmd-c-keystroke-to-the-active-application-in-objective-c-or-tell
I tried the applescript suggested with NSAppleScript:
NSLog(@"Hotkey Pressed");
NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
NSAppleScript *playScript;
playScript = [[NSAppleScript alloc] initWithSource:@"tell application \"System Events\" to keystroke \"c\" using command down"];
if([playScript isCompiled] == NO){
[playScript compileAndReturnError:nil];
}
id exerror = [playScript executeAndReturnError:nil];
if(exerror == nil){
NSLog(@"Script Failed");
}
It works, but only on the first time I hit the hotkey. Each subsequent hit will not to grab the highlighted text. The generalPasteboard still contains the same contents as before the script is run again. Clearing the generalPasteboard before I run the code is no use, because then the code fails when attempting to read the pasteboard contents.
So I tried the next suggested solution:
CFRelease(CGEventCreate(NULL));
CGEventRef event1, event2, event3, event4;
event1 = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)50, true);
event2 = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)8, true);
event3 = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)8, false);
event4 = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)50, false);
CGEventPost(kCGHIDEventTap, event1);
CGEventPost(kCGHIDEventTap, event2);
CGEventPost(kCGHIDEventTap, event3);
CGEventPost(kCGHIDEventTap, event4);
The above should send the keystrokes Command + c, but all I get is a beep, and the pasteboard contents are unchanged.
I'm at wits end - can anyone enlighten me as to what I'm missing or point me out to what I'm overlooking for something so simple?