I have traced this extremely annoying bug all the way back to Windows XP, so this is in fact now a 17 year old bug that has still not been fixed(!).
This bug is also discussed here, but the thread is locked and you can't discuss this issue any further:
I managed to create a simple fix by loading
osk.exe into x64dbg, analyzing what the problem was, and then patching the code using the debugger (see below for instructions).
What is happening is that
osk.exe is continuously storing the last active window in order to focus this window when the mouse hovers over OSK, or the user happens to activate OSK. This keeps the focus on the last active window at all times, which ensures that when you type with OSK the input goes where it should.
The problem is
osk.exe stops storing the active window when OSK is minimized.
This is the bug.
Now when you restore a minimized OSK it has amnesia, and only remembers the last active window from before it was minimized. So now it will focus this old window, instead of the previous real active window.
The "fix" that I used was to simply prevent OSK from ever forcing any window to become focused. You only have to patch one byte in
osk.exe for this fix, and that's why I chose it. Any other patch would have been extremely complicated otherwise.
In x64dbg you simply search for all references to
SetForegroundWindow. There are only two calls to this Win32 method. The first reference is the one to patch. There's an instruction
push eax just before the call to
SetForegroundWindow. Just replace
push eax with
ret, save to
osk.exe, and replace the original
osk.exe with this patched version.
It's not a 100% solution, because the auto-activate convenience of OSK is lost, but it's still better this way without the original annoyance. The auto-activation can be restored with AutoHotKey instead.
Leave a message here and I will post the script if anyone needs it. With the patch + AHK script, you have a fully working OSK without the annoying original bug.