有没有办法(当然有一种方法,但是哪种方式)以编程方式获取有关当前在Mac(OS 10.5.8和OS 10.6)上在iTunes中播放的歌曲的信息? 我需要这个用于我的Cocoa应用程序。 我使用iTunes 8和Objective-C。 ...
提示:本站收集StackOverFlow近2千万问答,支持中英文搜索,鼠标放在语句上弹窗显示对应的参考中文或英文, 本站还提供 中文繁体 英文版本 中英对照 版本,有任何建议请联系yoyou2525@163.com。
我目前正在开发一个 Safari 应用扩展,它由两部分组成:
此外,主机应用程序提供了一个全局快捷方式,可在状态栏中打开一个弹出窗口。 但是,我想检查哪个应用程序的 window 当前处于活动状态,因为如果 Safari window 当前处于活动状态,我不想打开弹出窗口。 有什么方法可以使用 Swift 找出哪个应用程序的 window 当前处于活动状态?
谢谢您的帮助。
因此,根据 Alexander 和 Wileke 的评论,我想我找到了解决方案。
使用NSWorkspace.shared.frontmostApplication
您可以检查 Safari 当前是否处于活动状态。 但正如 Wileke 所指出的,这并不意味着它有一个活跃的 window。 因此,我们使用CGWindowListCopyWindowInfo
首先获取所有windows,并通过比较PID检查其中是否至少有一个属于Safari。
这样,我们可以肯定地说 Safari 当前必须有一个活动的 window 接收关键事件。 This must be true as there is now way that Safari is front most without any windows or that Safari as an window but is not front most at the same time.
好吧,除非我错过了什么。 但现在它有效。
这是我想出的代码:
func safariIsActive() -> Bool {
// Get the app that currently has the focus.
let frontApp = NSWorkspace.shared.frontmostApplication!
// Check if the front most app is Safari
if frontApp.bundleIdentifier == "com.apple.Safari" {
// If it is Safari, it still does not mean, that is receiving key events
// (i.e., has a window at the front).
// But what we can safely say is, that if Safari is the front most app
// and it has at least one window, it has to be the window that
// crrently receives key events.
let safariPID = frontApp.processIdentifier
// With this procedure, we get all available windows.
let options = CGWindowListOption(arrayLiteral: CGWindowListOption.excludeDesktopElements, CGWindowListOption.optionOnScreenOnly)
let windowListInfo = CGWindowListCopyWindowInfo(options, CGWindowID(0))
let windowInfoList = windowListInfo as NSArray? as? [[String: AnyObject]]
// Now that we have all available windows, we are going to check if at least one of them
// is owned by Safari.
for info in windowInfoList! {
let windowPID = info["kCGWindowOwnerPID"] as! UInt32
if windowPID == safariPID {
return true
}
}
}
return false
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.