问题
I have searched on StackOverflow a lot about this topic. And what I have found so far was of great use. But now, I came to a very interesting fact.
In my case, I hide the app via NSApp hide:self
I then add a character to the pasteboard, and then try to input it in the frontmost application via CGEvents. My Code for this is as follows:
-(void)applicationDidHide:(NSNotification *)notification{
stringToInsert = @"©";
NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
[pasteboard clearContents];
NSArray *copiedObjects = [NSArray arrayWithObject:stringToInsert];
[pasteboard writeObjects:copiedObjects];
//Use CGEvents to "press" Cmd-V
CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);
CGEventRef pasteCommandDown = CGEventCreateKeyboardEvent(source, (CGKeyCode)9, YES);
CGEventSetFlags(pasteCommandDown, kCGEventFlagMaskCommand);
CGEventRef pasteCommandUp = CGEventCreateKeyboardEvent(source, (CGKeyCode)9, NO);
CGEventPost(kCGAnnotatedSessionEventTap, pasteCommandDown);
CGEventPost(kCGAnnotatedSessionEventTap, pasteCommandUp);
CFRelease(pasteCommandUp);
CFRelease(pasteCommandDown);
CFRelease(source);
}
My problem is that it doesn't want to insert text when I'm running it from within XCode without breaktpoints. It rather makes the mac's characteristic "plong" if he's uncapable os something.
But if I set a breakpoint to the method itself, and then jump by line, it curiously inserts it at instant.
Sorry for my bad English and for my perhaps bad text formatting as I'm new here on stackoverflow.
If you could help, I would really appreciate it!
回答1:
I've seen this before, and my guess is that the events are getting posted too quickly for the system to handle (since it really only has to handle no more than, say, 20 key events a second). I'd guess that putting in something like usleep(100000) (pause the thread for 1/10 of a second) would help quite significantly.
来源:https://stackoverflow.com/questions/6239140/cgkeyevent-pasting-working-with-breakpoints-but-not-without