autohotkey 如何激活上次打开的 window 更改其 pid

autohotkey how to activate last opened window that changes its pid

我正在尝试设置热键以始终启动新的 WindowsTerminal window 并为其提供焦点。即使存在现有的 window,我也总是希望它创建一个新的 window。我能够将新的 window 变为 运行,但我很难将其设为活动 window。

Run 命令期间捕获 pid 并使用 ahk_pid 似乎不起作用,因为 pid 在启动和出现的活动 window 之间发生变化(msgbox 调试显示一个pid,Window 间谍显示不同的 pid)。使用 WinWait, ahk_exe WindowsTerminal.exe 似乎 return 立即抓住一个预先存在的 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

我尝试创建包含 PID 的前后数组以确定哪个进程是新创建的进程,但针对下面创建的数组中的最后一个 PID 似乎按原样工作。

代码:

#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