Windows 10 Python: get PID from window handle

Mikelin

New Member
hi I am trying to get PID from the foreground window, but this doesn't work because I am passing the wrong kind of handle to the function. This is under python.

How do I fix this?
thx!


Code:
import ctypes
import time

time.sleep(2)
handle = ctypes.windll.user32.GetForegroundWindow()
print(handle)
PID = ctypes.windll.kernel32.GetProcessId(handle)
print (PID)
 

Neemobeer

Windows Forum Team
Staff member
Well the handle being returned from GetForegroundWindow is actually a handle to the Window and not the parent process. You can get the Thread process Id of the Window with ctypes.windll.user32.GetWindowThreadProcessId(handle) and from there you may be able to get the spawning process handle and then call GetProcessId on that handle.
 

AceInfinity

Senior Member
Microsoft MVP
Well the handle being returned from GetForegroundWindow is actually a handle to the Window and not the parent process. You can get the Thread process Id of the Window with ctypes.windll.user32.GetWindowThreadProcessId(handle) and from there you may be able to get the spawning process handle and then call GetProcessId on that handle.
GetWindowThreadProcessId can be used to get the PID directly without the need for GetProcessId.
 
Top