安装WIN32API和psutil第三方库
pip install pypiwin32
pip install psutil
下面列出了四种应用场景:
一,获取句柄及名称
import win32gui
hwnd_title = dict()
def get_all_hwnd(hwnd, mouse):
if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
hwnd_title.update({hwnd: win32gui.GetWindowText(hwnd)})
if __name__ in "__main__":
win32gui.EnumWindows(get_all_hwnd, 0)
for h, t in hwnd_title.items():
if t is not "":
print(h, t)
二,根据进程标题名称隐藏运行进程
import win32gui
from win32.lib import win32con
def handle_window(hwnd, extra):
if win32gui.IsWindowVisible(hwnd):
if '需要隐藏的程序标题名称' in win32gui.GetWindowText(hwnd):
win32gui.ShowWindow(hwnd, win32con.SW_HIDE)
if __name__ == '__main__':
win32gui.EnumWindows(handle_window, None)
# win32gui.EnumWindows(枚举函数名称, None) 语句是进行句柄ID枚举
# win32gui.GetWindowText(句柄ID) 语句是通过句柄ID来获取进程名称
# win32gui.IsWindowVisible(句柄ID) 语句是查询此句柄ID是否存在,存在返回1 否则返回0
# win32gui.ShowWindow(句柄ID, win32con.SW_HIDE) 语句是通过指定句柄ID来隐藏进程
三,根据程序名称来获取进程PID,然后通过PID杀掉进程
import win32gui
import win32process
import psutil
def handle_window(hwnd, extra):
if win32gui.IsWindowVisible(hwnd):
if '程序标题' in win32gui.GetWindowText(hwnd): # 判断是否符合
_,PID = win32process.GetWindowThreadProcessId(hwnd) # 通过句柄ID查询进程PID(第0个元素不管,第1个元素是PID)
p = psutil.Process(PID) # 实例化PID
p.terminate() # 关闭PID进程
if __name__ in "__main__":
win32gui.EnumWindows(handle_window, None) # 通过句柄ID查询PID并关闭PID
四,根据PID查询,返回句柄ID
import win32gui
import win32process
def get_hwnds_for_pid(pid):
# 通过PID查询句柄ID
def callback(hwnd, hwnds):
if win32gui.IsWindowVisible(hwnd) and win32gui.IsWindowEnabled(hwnd):
_, found_pid = win32process.GetWindowThreadProcessId(hwnd)
if found_pid == pid:
hwnds.append(hwnd)
return True
hwnds = []
win32gui.EnumWindows(callback, hwnds)
hwndy = 0
if hwnds:
hwndy = hwnds[0]
return hwndy
if __name__ in "__main__":
get_hwnds_for_pid(传入PID值) # 传入PID值后返回句柄ID