Sending a Cmd-V keystroke
Sending a Cmd-V keystroke
- Subject: Sending a Cmd-V keystroke
- From: Jim Graham <email@hidden>
- Date: Fri, 26 Mar 2010 00:23:04 +0000
Hi
This is a problem that occurred a few months back in a project. I Never actually used it in the project but it has bugged me ever since. I have simplified the problem into a small example
There is a window with three NSTextFields and a button. The button is connected to the doPaste action and the fields are outlets
Here is the code
-(IBAction)doPaste:(id)sender{
NSPasteboard *pb = [NSPasteboard generalPasteboard];
[pb declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:self];
[pb setString:@"Field 1" forType:NSStringPboardType];
[textField1 becomeFirstResponder];
[self pasteIt];
[pb setString:@"Field 2" forType:NSStringPboardType];
[textField2 becomeFirstResponder];
[self pasteIt];
[pb setString:@"Field 3" forType:NSStringPboardType];
[textField3 becomeFirstResponder];
[self pasteIt];
}
-(void)pasteIt{
CGEventSourceRef sourceRef = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);
if (!sourceRef)
{
NSLog(@"No event source");
return;
}
//9 = "v"
CGEventRef eventDown = CGEventCreateKeyboardEvent(sourceRef, (CGKeyCode)9, true);
CGEventSetFlags(eventDown, kCGEventFlagMaskCommand);
CGEventRef eventUp = CGEventCreateKeyboardEvent(sourceRef, (CGKeyCode)9, false);
CGEventPost(kCGHIDEventTap, eventDown);
CGEventPost(kCGHIDEventTap, eventUp);
CFRelease(eventDown);
CFRelease(eventUp);
CFRelease(sourceRef);
}
I expected that each of the fields would have their respective text pasted into them. What actually happens is that the last field gets three copies of it's text, Field 3, pasted into it. The other two fields are blank.
Can anybody explain why that should happen.
Jim Graham_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden