Im using the function to retrieve the
ParentProcessId of the browser chrome, as it launch multiple instances
Using comobj it takes around 5sec to find the pid, with your function 500ms, its still a high time, taking in count when you have multiple instances of the browser.
Do you have any other idea to retrieve the 'main' PID of a chrome instance?
Code: Select all
WinGet, BrowserPID, PID, New Tab - Google Chrome
arr := GetPID("chrome.exe")
;-----------------------------------------------------------
Time := (A_TickCount)
For PID in arr["chrome.exe"] {
If (PID = BrowserPID)
Continue
Parent := GetProperty(PID, "ParentProcessId")
}
Time := (A_TickCount - Time)
FileAppend, Time: %Time%`n,*
;-----------------------------------------------------------
Time := (A_TickCount)
For PID in arr["chrome.exe"] {
If (PID = BrowserPID)
Continue
Parent := GetProcessParent(PID)
}
Time := (A_TickCount - Time)
FileAppend, Time: %Time%`n,*
Return
GetPid(proc, proc2:="") {
; WTSEnumerateProcessesEx()
; https://www.autohotkey.com/boards/viewtopic.php?t=19323
static hWTSAPI := DllCall("LoadLibrary", "str", "wtsapi32.dll", "ptr")
If !(DllCall("wtsapi32\WTSEnumerateProcessesEx", "ptr", 0, "uint*", 0, "uint", -2, "ptr*", buf, "uint*", TTL))
Throw Exception("WTSEnumerateProcessesEx failed", -1)
addr := buf
arr := {}
arr[proc] := []
If (proc2)
arr[proc2] := []
Loop %TTL% {
ProcessName := StrGet(NumGet(addr+8, "ptr"))
If (ProcessName = proc) or (ProcessName = proc2) {
PID := NumGet(addr+4, "uint")
;WinGetTitle, Title, ahk_pid %PID%
arr[ProcessName][PID]:=1
}
addr += 8 + (A_PtrSize * 2)
}
If !(DllCall("wtsapi32\WTSFreeMemoryEx", "int", 0, "ptr", buf, "uint", TTL))
Throw Exception("WTSFreeMemoryEx failed", -1)
Return arr
}
GetProperty(Pid, Property) {
Select = Select %Property% from Win32_Process where ProcessId= %pid%
For process in ComObjGet("winmgmts:").ExecQuery(Select)
Return, process[Property]
}
GetProcessParent(PID) {
static MAX_PATH := 260, TH32CS_SNAPPROCESS := 2
hSnap := DllCall("CreateToolhelp32Snapshot", "UInt", TH32CS_SNAPPROCESS, "UInt", 0, "Ptr")
VarSetCapacity(PROCESSENTRY32, sz := 4*7 + A_PtrSize*2 + MAX_PATH << !!A_IsUnicode, 0)
NumPut(sz, PROCESSENTRY32, "UInt")
DllCall("Process32First", "Ptr", hSnap, "Ptr", &PROCESSENTRY32)
Loop {
if NumGet(PROCESSENTRY32, 4*2, "UInt") = PID {
ParentPID := NumGet(PROCESSENTRY32, 4*4 + A_PtrSize*2, "UInt")
break
}
} until !DllCall("Process32Next", "Ptr", hSnap, "Ptr", &PROCESSENTRY32)
DllCall("CloseHandle", "Ptr", hSnap)
Return ParentPID
}