如何在 OS X 上以编程方式粘贴?
我可以访问一般的NSPasteboard
.我在粘贴板上写了我的 NSData
.
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];
现在我想以编程方式粘贴.文本光标在另一个应用程序中的正确位置闪烁.按 ⌘ + V 有效.
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?
如果你想在自己的应用中执行粘贴动作,那么你可以使用 Responder Chain 发送 paste:
动作致第一响应者:
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];
文档说明了当您将 nil
作为 to:
参数传递时会发生什么:
The documentation says what happens when you pass nil
as the to:
parameter:
如果 aTarget 为 nil,则 sharedApplication 会查找可以响应消息的对象——即实现与 anAction 匹配的方法的对象.它从关键窗口的第一响应者开始.
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.
但是,如果您想在另一个应用中执行粘贴操作,则没有真正的好方法.最好的情况是执行假装"cmd-v 操作,并希望这意味着在目标应用程序中粘贴"...
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);
正如在另一条评论中提到的,这是一种粗暴的做法.它有点不安全(你并不总是知道 cmd-v 是什么意思)并且非常hackish.
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.