python根据进程名获取窗口句柄hwnd

1、安装pywin32

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pywin32

from ctypes import *

import win32con

import win32gui

import win32api

import win32process

import subprocess

import time

def find_process(exe_name):

hwnd_list = []

win32gui.EnumWindows(lambda _hwnd, _hwnd_list: _hwnd_list.append(_hwnd), hwnd_list)

app_hwnd = None

app_pid = None

for hwnd in hwnd_list:

app_pid,procname= get_process_name(hwnd)

if procname.find(exe_name) > 0:

app_hwnd = hwnd

print(procname)

break

if not app_hwnd:

print("没有找到hwnd")

return app_pid, app_hwnd

def get_process_name(hwnd):

try:

threadpid, procpid = win32process.GetWindowThreadProcessId(hwnd)

mypyproc = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, procpid)

procname = win32process.GetModuleFileNameEx(mypyproc, 0)

return procpid,procname

except:

return {0,"noprocname"}

def main():

# subprocess.Popen(r"C:\Program Files (x86)\Foxit Software\Foxit PhantomPDF\FoxitPhantomPDF.exe")

# time.sleep(5)

# app_pid, app_hwnd =find_process("FoxitPhantomPDF.exe")

app_pid, app_hwnd =find_process("WeChat.exe")

if app_hwnd != None:

print("找到了")

win32gui.SetForegroundWindow(app_hwnd)

if __name__ == '__main__':

main()