在Cocoa中的活动应用程序中获取当前选定的文本

Geo*_*org 15 macos service cocoa accessibility

我有一个状态菜单应用程序,可以使用系统范围的快捷方式启动.当应用程序处于活动状态时,如果我能够以某种方式获取当前正在运行的应用程序中选择的文本,那将会很棒.

例如,我在文本编辑器中输入内容,选择文本,点击我的全局快捷方式,我的应用程序出现,我现在想知道文本编辑器中的选定文本.

到目前为止我所拥有的是(如何通过Accessibility API获取当前所选文本的全局屏幕坐标的代码.)

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);
Run Code Online (Sandbox Code Playgroud)

这里的问题是它不能与Safari和Mail等应用程序一起使用...

谢谢

Bog*_*rca 1

这其实很简单,kAXSelectedTextAttribute是你的朋友。

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
    }
}
Run Code Online (Sandbox Code Playgroud)