如果想在Windows操作系统上使用Python去做一些自动化工作,pywin32模块常常会被用到,它方便了我们调用Windows API。
通过命令pip install pywin32 进行安装。安装完成后,在Lib/site-packages下,能够找到PyWin32.chm文档,通过该文档能查看每一个函数的具体用法。
import win32gui import win32process def get_hwnd_list(window_text): """ 获取窗口的句柄 :param window_text: str> :return hwnd_list: list> """ def callback(hwnd, hwnd_list): if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd): if window_text in win32gui.GetWindowText(hwnd): hwnd_list.append(hwnd) return True hwnd_list = list() win32gui.EnumWindows(callback, hwnd_list) return hwnd_list def get_pid_title_mapping(window_text): """ 获取窗口的pid和title :param window_text: str> :return pid_title_mapping: dict> """ hwnd_list = get_hwnd_list(window_text) pid_title_mapping = dict() for hwnd in hwnd_list: title = win32gui.GetWindowText(hwnd) thread_id, process_id = win32process.GetWindowThreadProcessId(hwnd) pid_title_mapping.update({process_id: title}) return pid_title_mapping if __name__ == ‘__main__‘: print(get_pid_title_mapping(‘PyWin32‘))
在该例中, 主要用到了win32gui.GetWindowText(hwnd)通过窗口的标题名获取窗口句柄,得到窗口句柄后通过win32process.GetWindowThreadProcessId(hwnd)获取窗口的进程PID。
程序会检测窗口名是否含有给定的关键字,以字典的形式返回含有关键字的窗口名及进程PID。当开启多个PyWin32.chm文档时,运行结果如下所示:
{14820: ‘PyWin32‘, 14696: ‘PyWin32‘}
未完待续...
参考资料
原文:https://www.cnblogs.com/zhuosanxun/p/14647950.html