How to paste programmatically on OS X?

穿精又带淫゛_ 提交于 2019-12-08 03:32:50

问题


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?


回答1:


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.




回答2:


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];



来源:https://stackoverflow.com/questions/19755942/how-to-paste-programmatically-on-os-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!