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)
本文介绍了一种通过Python获取指定进程名对应的主窗口句柄的方法。利用psutil和PyWin32库,遍历所有窗口并筛选出所需进程的窗口句柄。

5643

被折叠的 条评论
为什么被折叠?



