MacOSX: get foremost window title

匿名 (未验证) 提交于 2019-12-03 02:05:01

问题:

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.

What would be a way to get the window title anyway, even for cases like Texmaker?

回答1:

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.



回答2:

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.



回答3:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!