在给定 Window ID
的情况下,我将如何以编程方式激活 macOS 上的窗口(不属于我的应用程序),即移动到前面并聚焦窗口。我的应用程序将在用户授予辅助功能等权限的情况下运行。
令人惊讶的是,Quartz Window Services page 上没有描述的功能似乎是这样做的。
我目前正在使用 Swift,但我愿意使用 Objective-C、AppleScript 或其他任何东西。
编辑:
我不想将父应用程序的所有窗口置于最前面 - 只有与窗口 ID 匹配的特定窗口。
编辑:
我知道 NSWindow
类型仅用于引用当前进程的窗口,但是没有表示外部应用程序拥有的窗口的类吗?就像我们有 NSRunningApplication
来引用任何正在运行的应用程序(包括外部应用程序)一样,我期待一个 API 来处理所有打开的窗口(假设有正确的权限)。是否有像 NSOpenWindow
或 CGWindow
这样的类埋在某处?
最佳答案
我还没有找到切换到特定窗口的方法,但是您可以使用此功能切换到包含特定窗口的应用程序:
func switchToApp(withWindow windowNumber: Int32) {
let options = CGWindowListOption(arrayLiteral: CGWindowListOption.excludeDesktopElements, CGWindowListOption.optionOnScreenOnly)
let windowListInfo = CGWindowListCopyWindowInfo(options, CGWindowID(0))
guard let infoList = windowListInfo as NSArray? as? [[String: AnyObject]] else { return }
if let window = infoList.first(where: { ($0["kCGWindowNumber"] as? Int32) == windowNumber}), let pid = window["kCGWindowOwnerPID"] as? Int32 {
let app = NSRunningApplication(processIdentifier: pid)
app?.activate(options: .activateIgnoringOtherApps)
}
}
按名称切换可能也很有用:
func switchToApp(named windowOwnerName: String) {
let options = CGWindowListOption(arrayLiteral: CGWindowListOption.excludeDesktopElements, CGWindowListOption.optionOnScreenOnly)
let windowListInfo = CGWindowListCopyWindowInfo(options, CGWindowID(0))
guard let infoList = windowListInfo as NSArray? as? [[String: AnyObject]] else { return }
if let window = infoList.first(where: { ($0["kCGWindowOwnerName"] as? String) == windowOwnerName}), let pid = window["kCGWindowOwnerPID"] as? Int32 {
let app = NSRunningApplication(processIdentifier: pid)
app?.activate(options: .activateIgnoringOtherApps)
}
}
示例:switchToApp(named: "OpenOffice")
在我的 Mac 上,OpenOffice 是从带有 kCGWindowNumber = 599
的窗口启动的,所以这具有相同的效果:switchToApp(withWindow: 599)
据我所知,您的选项似乎是显示应用程序的当前事件窗口,或显示所有窗口(使用 .activateAllWindows
作为激活选项)
关于swift - 使用窗口 ID 激活窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47152551/