If you pay close attention, you'll notice that it does activate, but it does not bring it forward. That's because of the msgbox. When the msgbox closes, it automatically falls back to what was behind it, that being Chrome (you can see this by looking at the icon on the taskbar). If you have it minimized, run the script, hit ok, re-minimize chrome, click/activate another window that isn't the msgbox, then hit ok again, it will work. To get around that, you can save the PID, check if it's minimized and restore the window if it is, then activate it.
msgbox It should open when you click OK
cpid:=GetOldestPIDFromProcessName("chrome.exe")
WinGet, windowState, MinMax, % "ahk_pid " cpid
if(windowState=-1)
WinRestore, % "ahk_pid " cpid
WinActivate, % "ahk_pid " cpid
msgbox It should open again
cpid:=GetOldestPIDFromProcessName("chrome.exe")
WinGet, windowState, MinMax, % "ahk_pid " cpid
if(windowState=-1)
WinRestore, % "ahk_pid " cpid
WinActivate, % "ahk_pid " cpid
Similarly, you can make it a function for condensed code (whole code).
msgbox It should open when you click OK
ActivateWindow("chrome.exe")
msgbox It should open again
ActivateWindow("chrome.exe")
GetOldestPIDFromProcessName(strProcessName) {
for oProc in ComObjGet("winmgmts:").ExecQuery("Select ProcessID,CreationDate from Win32_Process WHERE Name = '" strProcessName "'") {
nOldestPID := (nOldestPIDCreationDate > oProc.CreationDate) ? oProc.ProcessID : nOldestPID ? nOldestPID : oProc.ProcessID
nOldestPIDCreationDate := oProc.CreationDate
}
return nOldestPID
}
ActivateWindow(strProcessName){
cpid:=GetOldestPIDFromProcessName(strProcessName)
WinGet, windowState, MinMax, % "ahk_pid " cpid
if(windowState=-1)
WinRestore, % "ahk_pid " cpid
WinActivate, % "ahk_pid " cpid
}
* I fixed the formatting, because it was bothering me.