gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 02:09:38 26 4
gpt4 key购买 nike

我可以访问一般的 NSPasteboard。我将我的 NSData 写入了粘贴板。

NSPasteboard *pboard = [NSPasteboard generalPasteboard];

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

现在我想以编程方式粘贴文本光标另一个应用中的正确位置闪烁。按 ⌘ + V 即可。

有人知道吗?也许如何以编程方式调用快捷方式进行粘贴?

最佳答案

如果您想在自己的应用程序中执行粘贴操作,那么您可以使用响应链将paste: 操作发送给第一响应者:

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

文档说明了当您将 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. It begins with the first responder of the key window.

但是,如果您想在另一个 应用程序中执行粘贴操作,则没有真正好的方法。您所能期望的最好结果是执行“假装”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);

正如另一条评论中提到的,这是一种粗暴的做法。它有点不安全(您并不总是知道 cmd-v 是什么意思)并且非常黑。

关于objective-c - 如何在 OS X 上以编程方式粘贴?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19755942/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com