当用户在我正在构建的 mac OS 应用程序中按下快捷方式时,我试图获取选定的文本。我正在尝试使用 AppleScript 来执行此操作,该 AppleScript 使用剪贴板进行黑客攻击。但这并不适用于所有应用程序。
func readSelectedText() {
let script = """
-- Back up clipboard contents:
set savedClipboard to the clipboard
-- Copy selected text to clipboard:
tell application "System Events" to keystroke "c" using {command down}
delay 1 -- Without this, the clipboard may have stale data.
set theSelectedText to the clipboard
delay 1 -- Without this delay, may restore clipboard before pasting.
-- Restore clipboard:
set the clipboard to savedClipboard
return theSelectedText
"""
var error: NSDictionary?
if let appleScript = NSAppleScript(source: script), let output = appleScript.executeAndReturnError(&error).stringValue {
print("Selected text:", output)
} else {
print("AppleScriptError: \(String(describing: error))")
}
}
是否有在任何应用程序中执行此操作的可靠方法?
这里是一些示例代码,可让您从任何地方选择(复制,命令+c)一些文本,并将
get
它放入您的应用程序中。
struct ContentView: View {
@State var txt = "select (copy) some text, then click the button"
var body: some View {
Button("Show selected text") {
if let str = NSPasteboard.general.string(forType: .string) {
txt = str
}
}
Text(txt)
}
}