1
votes

I'm trying to setup a hotkey to always launch a new WindowsTerminal window and give it focus. Even if there is an existing window, I always want it to create a new window. I'm able to get the new window to run, but I'm having difficulty making it the Active window.

Capturing the pid during the Run command and using ahk_pid doesn't seem to work as the pid changes between launch and the active window that appears (msgbox debugging shows one pid, Window Spy shows a different pid). Using WinWait, ahk_exe WindowsTerminal.exe seems to return right away grabbing a pre-existing window.

#t::
Run, wt.exe, , , TermPid

;; TermPid seems to change between the launch and the final window that appears
WinWait, ahk_pid %TermPid%, , 3
if ErrorLevel {
  MsgBox, WinWait timed out... %TermPid%
  return
} else {
  WinActivate
}

;; problems when there are other already existing WindowsTerminal.exe windows
;WinWait, ahk_exe WindowsTerminal.exe, , 3
;if ErrorLevel {
;  MsgBox, WinWait timed out...
;  return
;} else {
;  WinActivate
;}

return
2

2 Answers

1
votes

I tried to create before and after array containing the PIDs to determine which process was the newly created one, but targeting the last PID in the array created below seems to work as is.

Code:

#t::

Run, wt.exe
;If you are on a slow computer, you may need to increase this delay
Sleep 100 ;Forgot how to optimize this w/ WinWait, but not important rn bc its not critical
newArray:=[]

for proc in ComObjGet("winmgmts:").ExecQuery("Select * from Win32_Process"){
    
    
    
    
    if(proc.Name=="WindowsTerminal.exe"){
        prID := proc.ProcessId
        newArray.Push(prID)
    }
    
    
    
}


LastItem:=newArray[newArray.MaxIndex()]
WinActivate, ahk_pid %LastItem%

return
0
votes

You can use the RegisterShellHookWindow Function to activate the new window as soon as it is created:

#Persistent
SetBatchLines, -1
Process, Priority,, High
#SingleInstance Force

Gui +LastFound
hWnd := WinExist()
DllCall( "RegisterShellHookWindow", UInt,hWnd )
MsgNum := DllCall( "RegisterWindowMessage", Str,"SHELLHOOK" )
OnMessage( MsgNum, "ShellMessage" )
Return


#t:: Run, wt.exe


ShellMessage( wParam,lParam ) {
    If ( wParam = 1 ) ;  HSHELL_WINDOWCREATED := 1
    {
        WinGet, ProcName, ProcessName, ahk_id %lParam%
        If  ( ProcName = "WindowsTerminal.exe" ) 
            WinActivate, ahk_id %lParam%
    }
}