【问题标题】:Swift - Get file path of currently opened document in another applicationSwift - 获取另一个应用程序中当前打开的文档的文件路径
【发布时间】:2023-12-20 07:11:01
【问题描述】:

我正在尝试使用 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 一旦我做到了。任何帮助将不胜感激。

【问题讨论】:

    标签: swift xcode macos accessibility axuielement


    【解决方案1】:

    感谢来自@JamesWaldrop 的another post 的帮助,我能够自己回答这个问题,并想在这里为任何寻找类似内容的人发帖:

    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。仍然愿意接受其他可能更好或不使用辅助功能的方法。

    【讨论】:

    • 感谢您分享此内容。这正是我所需要的
    最近更新 更多