Trigger on window close?

Is it possible to trigger and action on a window being closed — and, specifically, to trigger pre-close?

What I'm trying to do is this:

  • If a Visual Studio Code window closes, remember its title (or, ideally, its workspace path) and position, and save them.
  • If a Visual Studio Code window opens (and not when it is just focused, so a Focused Window trigger wouldn't work here) and there is a saved position for that title (or workspace path), restore the window to the saved position.

Triggering on a hotkey is not ideal — I want this to happen automatically, every time.

And if you think Visual Studio Code should be able to cope with that sort of basic stuff itself, you'd be right. But it doesn't, despite a ticket having been opened in 2018 — only on full quit/restart.

There is no way to do this that I am aware of... and since you mention you want it to happen automatically, that would rule out using the hotkey ⌘W (which is what I use for some Finder macros to keep a list of recently closed directories).

You could of course use a periodic trigger in a macro group that works only in VSC. Perhaps not the most efficient, but it would likely work for what you need.

I haven't tried it myself but you might be able to come up with an AppleScript to monitor a specific application window for a close event that then triggers a KM macro.