I'm looking to write a script which outputs a list of all the window titles of all the currently running programs.
The easy, one-liner method of achieving this in AppleScript is:
tell application "System Events" to get the name of every window of ¬
(every process whose background only is false)
Annoyingly, this returns a nested lists, which you'll either have to loop through in a repeat with
block, or flatten the nest into a simple list (which isn't too hard).
Running AppleScript from the command line has the advantage that the returned data are in text format, which can be manipulated quite easily. You can even make use of the command line from within AppleScript to get the benefits of each:
do shell script "osascript -e \" ¬
set text item delimiters to tab
tell app \\\"system events\\\" to get name of every window of ¬
(every process whose background only is false)
return the result as text \" | egrep -oi -e '[^\t]+'"
return paragraphs of result
which returns a nice, straight forward, text list of window titles.
Finally, here's a formal AppleScript to get the job done properly, in a way that allows you to retain the ability to reference the window object if you need to get other properties or manipuoate it:
use application "System Events"
property R : {WindowTitle:missing value, AttachedToProcess:missing value}
set WindowList to {}
set P to a reference to (every process whose background only is false)
repeat with proc in P
set [proc] to proc
set W to (a reference to every window of proc)
repeat with _w in W
set [_w] to _w
copy R to end of WindowList
tell last item of WindowList
set its WindowTitle to title of _w
set its AttachedToProcess to name of proc
end tell
end repeat
end repeat
return WindowList
The resulting list is a list of records that have the structure of property R
. Each record represents a single window, which contains the window's title and the name of the process it belongs to, e.g. {WindowTitle:"Downloads", AttachedToProcess:"Finder"}
. This way, it's easy to do things with the window, such as:
set TheWindow to item 2 of WindowList --> {WindowTitle:"...", AttachedToProcess:"..."}
tell process named (TheWindow's ProcName) to ¬
tell window named (TheWindow's WindowTitle) to ¬
set [focused, position, size] to [true, {0, 0}, {400, 777}]
Best Answer
You want
unix id
. Like this...PS: Realize that not all "windows" returned by your original code are visible. So depending what you are trying to do you may want to also look into
https://stackoverflow.com/questions/14551419/listing-all-windows-of-all-applications
Google will give you other examples...