简体   繁体   English

如何在OS X上以编程方式粘贴?

[英]How to paste programmatically on OS X?

I have access to the general NSPasteboard . 我可以访问常规的NSPasteboard I wrote to the pasteboard my NSData . 我写了我的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. 按⌘+ V即可。

Somebody know how? 有人知道吗? Maybe how to paste with calling the shortcut programmatically? 也许如何通过编程方式调用快捷方式进行粘贴?

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: 如果要在自己的应用中执行粘贴操作,则可以使用“响应者链”将“ paste:操作发送给第一响应者:

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

The documentation says what happens when you pass nil as the to: parameter: 该文档说明了当您将nil作为to:参数传递时会发生什么:

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. 如果aTarget为nil,则sharedApplication将寻找一个可以响应消息的对象,即,一个实现与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... 您所希望的最好是执行“伪装” cmd - v操作,并希望这意味着在目标应用程序中“粘贴” ...

#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. 这有点不安全(您并不总是知道cmd - v的意思),而且有点黑。

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 鉴于键盘cmd + v可以工作,它确实具有粘贴:作为一种方法

call [target paste:nil];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM