@Nige_S Thanks for the suggestion, but I played with that and couldn't make it work.
While the desktop is nominally a Finder window, set w to every Finder window
doesn't see it. It only sees the windows themselves. desktop window
is a recognized noun, but it has no properties. Also, frontmost
is a property of the process, not a window. The "frontmost window" is just the window with index 1.
If the desktop is selected and there are no Finder windows, it's easy. Finder is the frontmost process, but set w to every window
followed by set n to count of w
gives 0.
The difficulty is if the desktop is selected, but there are other Finder windows. set w to every window
and set w to every Finder window
see all of the windows (other than the desktop), but give no direct information on whether item 1 of w
is the active window.
I also tried coming at it through System Events, telling process "Finder" things like set x to value of attribute 1 of item 1 of w.
(Attribute 1 is "AXFocused".) The result of that one is false, regardless of whether the window is selected.
I'm not an AppleScript guru by any means, but after a fair bit of poking around (including finding difficulties with how Script Debugger talks to System Events) I couldn't make it work. If there is a way to do it I'd love to see it, if for no other reason than I'd learn something.
Cdthomer's suggestion works. This returns 1 if Finder is frontmost with the desktop selected:
# Flag the situation where the Desktop is selected.
tell application "Finder"
set w to every Finder window
set nWindows to count of w
end tell
tell application "System Events"
set fp to every process whose frontmost is true
if (name of item 1 of fp) ≠ "Finder" then return 0
if nWindows = 0 then return 1
tell process "Finder"
set menuBar to menu bar 1
set canClose to value of attribute "AXEnabled" of menu item "Close Window" of menu "File" of menuBar
if canClose then return 0
return 1
end tell
end tell
But what I would really like to do is use pause until front window of front application exists
to wait for me to select a window. I can do that by looping the code above every .3 seconds or so, then breaking out of the loop when AXEnabled is true. But it's ugly...