gpt4 book ai didi

macos - 获取 Cocoa 中事件应用程序中当前选定的文本

转载 作者:行者123 更新时间:2023-12-03 16:02:46 34 4
gpt4 key购买 nike

我有一个状态菜单应用程序,可以使用系统范围的快捷方式启动。当应用程序处于事件状态时,如果我能够以某种方式获取在当前运行的应用程序中选择的文本,那就太好了。

例如,我在文本编辑器中输入一些内容,选择文本,点击全局快捷方式,我的应用程序就会出现,我现在很想知道从文本编辑器中选择的文本。

到目前为止,我所拥有的是以下内容(采用 How to get global screen coordinates of currently selected text via Accessibility APIs. 中的代码)

AXUIElementRef systemWideElement = AXUIElementCreateSystemWide();
AXUIElementRef focussedElement = NULL;
AXError error = AXUIElementCopyAttributeValue(systemWideElement, kAXFocusedUIElementAttribute, (CFTypeRef *)&focussedElement);
if (error != kAXErrorSuccess) {
NSLog(@"Could not get focussed element");
} else {
AXValueRef selectedTextValue = NULL;
AXError getSelectedTextError = AXUIElementCopyAttributeValue(focussedElement, kAXSelectedTextAttribute, (CFTypeRef *)&selectedTextValue);
if (getSelectedTextError == kAXErrorSuccess) {

selectedText = (__bridge NSString *)(selectedTextValue);
NSLog(@"%@", selectedText);
} else {
NSLog(@"Could not get selected text");
}
}
if (focussedElement != NULL) CFRelease(focussedElement);
CFRelease(systemWideElement);

这里的问题是它不适用于 Safari 和 Mail 等应用程序...

谢谢

最佳答案

这实际上非常简单,kAXSelectedTextAttribute 是你的 friend 。

extension AXUIElement {    
var selectedText: String? {
rawValue(for: kAXSelectedTextAttribute) as? String
}

func rawValue(for attribute: String) -> AnyObject? {
var rawValue: AnyObject?
let error = AXUIElementCopyAttributeValue(self, attribute as CFString, &rawValue)
return error == .success ? rawValue : nil
}
}

关于macos - 获取 Cocoa 中事件应用程序中当前选定的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19980020/

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