Detect window under mouse cursor

I am trying to replicate a BetterTouchTool action: close window below cursor

Basically, I'd like to detect which application window is under the mouse cursor at the moment I trigger the macro.

Then I'd like to focus that window and trigger a Command + W to close the window.

I'm struggling with the first part - detecting what is under the pointer. Any ideas?

That is because Keyboard Maestro cannot do that (unless you click to make that window the frontmost). There are some things that BetterTouchTool can do that Keyboard Maestro cannot which is why it's handy to have both Apps.

I think that's the solution actually. I made something for someone recently to send the window under the mouse to the back and it works fine because the first click only brings the window to the front; no issues with accidentally clicking elements.

Yes, this works quite well. The only issue is that if the window I'm closing is already at the front, then there is a risk of accidentally clicking something in the UI.

I thought I'd try a right-click instead, since that's less likely to do something undesirable. But unfortunately a right-click doesn't bring the window to the front.

BTT is surely a handy tool. I used it for several years, but found it didn't play nicely with my new Wacom. Even on my other computers (without Wacoms), I frequently had issues with laggy typing and CPU usage.

Keyboard Maestro seems much more refined and does 99% of what I need it to, in a more stable and, in my perception, less hacky way. The trade off for being better Mac citizen is some limitations with this kind of low level integration with the OS.

1 Like

This detects whether the mouse is over the front window. If it is, it closes it; if it's not, it clicks and then closes the front window.

Edit: updated to include additions suggested in subsequent posts.

Close Window Under Mouse.kmmacros (23 KB)

Macro screenshot

5 Likes

Thank you! This is working really nicely. I have swapped out the Close Window for a Command + W keystroke, since I often want to close only a tab in Safari or Finder. I also added Active to Last Application to the Otherwise block.

1 Like

I don't follow... What do you mean?

My typo... Activate Last Application

So after the macro clicks an application window in order close it, focus returns to where it was before running the macro.

1 Like

Good additions! I've updated the macro above to include them for anyone else who comes looking for a solution. :+1:t3:

1 Like