Run when all application windows have closed

I’m wondering if there’s a way to detect when the last window of an application has closed, and run a macro at that point.

Many applications for OSX continue to run even after all windows for that application have been closed (ex: Preview, Terminal, browsers, etc). I’d like to find a way to make applications actually quit once their last window has been closed. If anyone knows how to do this using KM please let me know.

Thanks!

There is no trigger for window changed/window opened/window closed because the system does not provide events for that, and so it would require polling to notice which is slow and inefficient.

You could trigger on application deactivation which is probably when you would want to perform the action anyway.

Then it is just a question of counting the number of open windows in the application. Keyboard Maestro has no ability to count the windows in the non-front application (and it would already be non-front by the time it had deactivated) so you would have to use some other means. Probably you can do it using AppleScript. The name of the application you just deactivated is available via the %TriggerValue% text token.

OK, thanks Peter. I’ll give the deactivation hook + AppleScript a shot.

Hey Ian,

For any scriptable application:

tell application "Terminal"
  if (count of windows) = 0 then
    quit
  end if
end tell

For non-scriptable applications:

tell application "System Events"
  if quit delay ≠ 0 then set quit delay to 0
  tell application process "App-Name"
    if (count of windows) = 0 then
      tell application "App-Name" to quit
    end if
  end tell
end tell

[Edited script two 2014/11/26 00:22 CST and fixed an error.]

Potentially an app could have a toolbar or info-window that shows up as a window in System Events - requiring some sort of work-around.

The only alternative I know of to Peter's suggestion is UI Actions by PFiddlesoft. It brings "Universal Attachability" for AppleScript to the System level and can watch for things like window-open/close events. By itself it's nearly as expensive as KM though.

--
Best Regards,
Chris

3 Likes