我正在尝试使用 swift 代码从另一个应用程序获取打开文档的文件路径。我知道如何在 AppleScript 中做到这一点,就像这样:
tell application "System Events"
if exists (process "Pro Tools") then
tell process "Pro Tools"
set thefile to value of attribute "AXDocument" of window 1
end tell
end if
end tell
这个 AppleScript 可以做我想做的事,但我希望能在 Swift 中原生完成。我知道一个选择是从我的程序运行这个脚本,但我希望找到另一种方法来实现它,可能不使用辅助功能。
在我的应用程序中,我可以通过执行以下操作将应用程序作为 AXUIElement 获取:
let proToolsBundleIdentifier = "com.avid.ProTools"
let proToolsApp : NSRunningApplication? = NSRunningApplication
.runningApplications(withBundleIdentifier: proToolsBundleIdentifier).last as NSRunningApplication?
if let app = proToolsApp {
app.activate(options: .activateAllWindows)
}
if let pid = proToolsApp?.processIdentifier {
let app = AXUIElementCreateApplication(pid)
}
我只是不确定在创建 AXUIElement 后如何处理它。任何帮助将不胜感激。
最佳答案
感谢another post的帮助来自@JamesWaldrop,我能够自己回答这个问题并想在这里发布给任何寻找类似东西的人:
let proToolsBundleIdentifier = "com.avid.ProTools"
let proToolsApp : NSRunningApplication? = NSRunningApplication
.runningApplications(withBundleIdentifier: proToolsBundleIdentifier).last as NSRunningApplication?
if let pid = proToolsApp?.processIdentifier {
var result = [AXUIElement]()
var windowList: AnyObject? = nil // [AXUIElement]
let appRef = AXUIElementCreateApplication(pid)
if AXUIElementCopyAttributeValue(appRef, "AXWindows" as CFString, &windowList) == .success {
result = windowList as! [AXUIElement]
}
var docRef: AnyObject? = nil
if AXUIElementCopyAttributeValue(result.first!, "AXDocument" as CFString, &docRef) == .success {
let result = docRef as! AXUIElement
print("Found Document: \(result)")
let filePath = result as! String
print(filePath)
}
}
这与 AppleScript 一样获取 AXDocument。仍然会对其他可能更好或不使用辅助功能的方法持开放态度。
关于Swift - 获取当前在另一个应用程序中打开的文档的文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49076103/