python:根据进程名获取主窗口句柄
具体运行性能暂不考虑,作为一种思路保存。代码如下:
import time
import psutil
from win32 import win32gui
from win32 import win32api
from win32 import win32process
strCmd="cmd.exe"
#map类型,键值为进程ID,value为窗口句柄。
mID2Handle={}
def get_all_hwnd(hwnd,mouse):
if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
nID=win32process.GetWindowThreadProcessId(hwnd)
#print(nID,win32gui.GetWindowText(hwnd))
del nID[0]
for abc in nID:
try:
pro=psutil.Process(abc).name()
except psutil.NoSuchProcess:
pass
else:
#print(abc,win32gui.GetWindowText(hwnd))
if pro == strCmd:
print("进程ID:",abc,"窗口句柄: ",hwnd,"标题: ",win32gui.GetWindowText(hwnd))
mID2Handle[abc]=hwnd
win32gui.EnumWindows(get_all_hwnd, 0)