This has drove me nuts always too, I had AI generate this AHK code for me (AutoHotkey, if not familiar with it). Copied below if you're still interested in a solution:
You'll have to get AI or yourself to adjust it for any windows/programs that you don't want the focus to be blocked....ie if you press Win-R for Run or Ctrl-Shift-Esc for Task Manager, it will send it to background, which you don't really want. I integrated it into my main AHK script that I have running all the time, so there is a flag that gets turned on and off for commands or shortcut keys or programs that I don't want focus to be blocked. I also have some other standalone scripts that run via voice commands or scheduled tasks, so had to add a flag in a file that the main script keeps an eye on to avoid blocking focus for other windows that I want to pop up when I ask for them. Very hard to make this transferable between users as everyone is organized differently, so I think it's best to use AI or your own coding knowledge to customize it to your own needs.
#NoEnv
#SingleInstance Force
SetTimer, WatchFocus, 100
UserSwitch := False
LastHwnd := ""
; These actions count as intentional switches
~LButton::
~RButton::
~MButton::
UserSwitch := True
SetTimer, ResetFlag, -600
return
~Alt & Tab::
~LWin & Tab::
UserSwitch := True
SetTimer, ResetFlag, -1500
return
ResetFlag:
UserSwitch := False
return
WatchFocus:
CurrentHwnd := WinExist("A")
if (LastHwnd = "") {
LastHwnd := CurrentHwnd
return
}
if (CurrentHwnd != LastHwnd) {
if (!UserSwitch) {
; Focus was stolen — restore it
WinActivate, ahk_id %LastHwnd%
} else {
; Intentional switch — accept it
LastHwnd := CurrentHwnd
}
}
return