macos MacOSX:获取最重要的窗口标题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5292204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MacOSX: get foremost window title
提问by Albert
I am using this code to get the window title:
我正在使用此代码来获取窗口标题:
tell application "System Events"
set frontApp to name of first application process whose frontmost is true
end tell
tell application frontApp
set window_name to name of front window
end tell
However, this fails in some cases. Obviously it fails when there is no open window but that is Ok. However, in some cases, for example for Texmaker, it fails with an error. It also doesn't work for Preview.
但是,这在某些情况下会失败。显然,当没有打开的窗口时它会失败,但没关系。但是,在某些情况下,例如对于Texmaker,它会因错误而失败。它也不适用于预览。
What would be a way to get the window title anyway, even for cases like Texmaker?
无论如何,即使对于像 Texmaker 这样的情况,获得窗口标题的方法是什么?
回答by Albert
This seems to work always:
这似乎总是有效:
global frontApp, frontAppName, windowTitle
set windowTitle to ""
tell application "System Events"
set frontApp to first application process whose frontmost is true
set frontAppName to name of frontApp
tell process frontAppName
tell (1st window whose value of attribute "AXMain" is true)
set windowTitle to value of attribute "AXTitle"
end tell
end tell
end tell
return {frontAppName, windowTitle}
Got the idea from here.
从这里得到了这个想法。
回答by user2330514
Building off of Albert's answer, I'd instead do
以阿尔伯特的答案为基础,我会这样做
global frontApp, frontAppName, windowTitle
set windowTitle to ""
tell application "System Events"
set frontApp to first application process whose frontmost is true
set frontAppName to name of frontApp
set windowTitle to "no window"
tell process frontAppName
if exists (1st window whose value of attribute "AXMain" is true) then
tell (1st window whose value of attribute "AXMain" is true)
set windowTitle to value of attribute "AXTitle"
end tell
end if
end tell
end tell
return {frontAppName, windowTitle}
This is a hack and I have no experience, but the advantage is that it doesn't crash if there's no window.
这是一个 hack,我没有经验,但优点是如果没有窗口,它不会崩溃。
回答by sakra
Give the following script a try:
试试下面的脚本:
tell application "System Events"
set window_name to name of first window of (first application process whose frontmost is true)
end tell
I haven't verified that it works for TextMaker, though.
不过,我还没有验证它是否适用于 TextMaker。