WinActivate doesn't set focus. The window or window manager sets focus when it gains activation.
The behaviour of saving/restoring focus when a window loses/gains focus is neither guaranteed nor implemented by AutoHotkey. It is implemented by the system function DefDlgProc, along with most other standard dialog behaviour.
The focus issue seems to be a consequence of restoring the window prior to activating it, although even that behaves as expected if the window was minimized by clicking its taskbar button. I was unable to determine exactly which combination of messages is causing the undesired switch of focus, but I could see that the Button has focus when focus is switched to the Edit.
This has the same effect:
Code: Select all
DllCall("ShowWindow", "ptr", WinExist("testgui"), "int", 9) ; SW_RESTORE
This appears to have the desired effect:
Code: Select all
hwnd := WinExist("testgui")
DllCall("SetForegroundWindow", "ptr", hwnd)
DllCall("ShowWindow", "ptr", hwnd, "int", 9) ; SW_RESTORE
Changing WinActivate to restore the window
after activation would avoid this issue, but I hesitate to do it because it may have other consequences; also, the documented behaviour is (emphasis added):
If the window is minimized and inactive, it is automatically restored prior to being activated.