macOS 在系统全局获取用户选中的文本

方法一:监听剪贴板

...
.task {
            await watch {copiedString in
                if settings.isListening {
                    if let copiedString = NSPasteboard.general.string(forType: .string) {
                        接收剪贴板文本的变量 = copiedString
                        DispatchQueue.main.async {
                            showPopView()
                        }
                    }
                }
            }
        }
...
func watch(using closure: @escaping (_ copiedString: String) -> Void) async {
        let pasteboard = NSPasteboard.general
        var changeCount = NSPasteboard.general.changeCount
        
        while isWatch {
            try? await Task.sleep(nanoseconds: 1_000_000_000)
            guard let copyString = pasteboard.string(forType: .string),
                  pasteboard.changeCount != changeCount else { continue }
            
            changeCount = pasteboard.changeCount
            closure(copyString)
        }
    }
上述代码放在某个View中即可
 

方法二:Accessibility APIs

import ApplicationServices
import Cocoa

func getSelectedText() -> String? {
    let systemWideElement = AXUIElementCreateSystemWide()

    var selectedTextValue: AnyObject?
    let errorCode = AXUIElementCopyAttributeValue(systemWideElement, kAXFocusedUIElementAttribute as CFString, &selectedTextValue)
    
    if errorCode == .success {
        let selectedTextElement = selectedTextValue as! AXUIElement
        var selectedText: AnyObject?
        let textErrorCode = AXUIElementCopyAttributeValue(selectedTextElement, kAXSelectedTextAttribute as CFString, &selectedText)
        
        if textErrorCode == .success, let selectedTextString = selectedText as? String {
            return selectedTextString
        } else {
            return nil
        }
    } else {
        return nil
    }
}
This requires setting Privacy - AppleEvents Sending Usage Description in Info.plist and setting com.apple.security.temporary-exception.apple-events to have com.apple.systemevents.
6th line in Keys
6th line in Keys
last 2 lines in Keys
last 2 lines in Keys
你觉得这篇文章怎么样?
YYDS
比心
加油
菜狗
views

Loading Comments...