Question

I have access to the general NSPasteboard. I wrote to the pasteboard my NSData.

NSPasteboard *pboard = [NSPasteboard generalPasteboard];

[pboard clearContents];
[pboard setData:newContent forType:type];

Now I want to paste programmatically. The text cursor is blinking on the correct position in another app. Hitting ⌘ + V works.

Somebody know how? Maybe how to paste with calling the shortcut programmatically?

Was it helpful?

Solution

If you want to perform the paste action in your own app, then you can use the Responder Chain to send the paste: action to the first responder:

[NSApp sendAction:@selector(paste:) to:nil from:self];

The documentation says what happens when you pass nil as the to: parameter:

If aTarget is nil, sharedApplication looks for an object that can respond to the message—that is, an object that implements a method matching anAction. It begins with the first responder of the key window.

However, if you want to perform the paste action in another app, there's no real good way to do that. The best you can hope for is to perform a "pretend" cmd-v operation and hope that that means "paste" in the target app...

#import <Carbon/Carbon.h>

CGEventSourceRef source = CGEventSourceCreate(kCGEventSourceStateCombinedSessionState);
CGEventRef pasteCommandDown = CGEventCreateKeyboardEvent(source, kVK_ANSI_V, YES);
CGEventSetFlags(pasteCommandDown, kCGEventFlagMaskCommand);

CGEventRef pasteCommandUp = CGEventCreateKeyboardEvent(source, kVK_ANSI_V, NO);

CGEventPost(kCGAnnotatedSessionEventTap, pasteCommandDown);
CGEventPost(kCGAnnotatedSessionEventTap, pasteCommandUp);

CFRelease(pasteCommandUp);
CFRelease(pasteCommandDown);
CFRelease(source);

As mentioned in another comment, this is kind of a gross way to do it. It's somewhat unsafe (you don't always know what cmd-v means) and is pretty hackish.

OTHER TIPS

Assuming a non-custom view:

when a view conforms to copy & paste, it has a copy and a paste method. GIVEN that the keyboard cmd+v works, it does indeed have paste: as a method

call [target paste:nil];

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top