MacOS – Activate desktop using Applescript

applescriptdesktopfindermacos

Basically, I have this short script to "clean up" the desktop. This is the code:

tell application "System Events"
    tell application "Finder" to activate desktop
    delay 0.1
    tell process "Finder" to click menu item "Clean Up" of menu "View" of menu bar item "View" of front menu bar
end tell

The script works fine when there are no Finder windows open. However, if there is at least one Finder window, when the line tell application "Finder" to activate desktop is run, it will make that window active, rather than the desktop.

What is the reason for this? And what is the correct way to put the focus on the desktop (same effect as clicking on the desktop image)?

(Doing this on El Capitan)

Best Answer

Here is some code I could make work on my "Capitan":

tell application "System Events"
  tell application "Finder" to activate
  repeat while (value of attribute "AXfocused" of group 1 of scroll area of ¬
     process "Finder" is {false})
        keystroke "<" using command down
  end repeat
end tell

The repeat-loop checks whether "group 1 of scroll area" --which to my surprise "is" Desktop-- is "AXFocused" (meaning finder's active "window").
If NOT so, it keystrokes "cmd <" (on a German keyboard), which is identical to finder's:
<menu: "Windows" / "Next window"> menu item.
You will see some or all of your windows brought to front ONCE.

(I tried all kinds of "clicks", "selects" and the like beforehands to no avail ...)