首页 > 解决方案 > autohotkey如何激活最后打开的窗口来改变它的pid

问题描述

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

Run在命令和使用期间捕获 pidahk_pid似乎不起作用,因为 pid 在启动和出现的活动窗口之间发生变化(msgbox 调试显示一个 pid,Window Spy 显示一个不同的 pid)。使用WinWait, ahk_exe WindowsTerminal.exe似乎立即返回抓住一个预先存在的窗口。

#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

标签: autohotkey

解决方案


我尝试在包含 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

推荐阅读