[Python] 纯文本查看 复制代码 import win32gui
import win32con
import win32process
import psutil
def get_process_name(hwnd):
"""根据窗口句柄获取进程名(如 'QQ.exe')"""
try:
_, pid = win32process.GetWindowThreadProcessId(hwnd)
process = psutil.Process(pid)
return process.name().lower()
except Exception:
return None
def is_valid_main_window(hwnd):
"""判断是否为可置顶的主窗口(过滤掉托盘小窗口等)"""
if not win32gui.IsWindowVisible(hwnd):
return False
# 过滤掉没有标题的窗口
title = win32gui.GetWindowText(hwnd)
if not title.strip():
return False
# 过滤掉尺寸过小的窗口(例如托盘图标窗口可能只有几十像素)
rect = win32gui.GetWindowRect(hwnd)
width = rect[2] - rect[0]
height = rect[3] - rect[1]
if width < 200 or height < 200:
return False
return True
def set_topmost(hwnd):
"""将指定窗口设为总在最前"""
ex_style = win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE)
ex_style |= win32con.WS_EX_TOPMOST
win32gui.SetWindowLong(hwnd, win32con.GWL_EXSTYLE, ex_style)
win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST,
0, 0, 0, 0,
win32con.SWP_NOMOVE | win32con.SWP_NOSIZE | win32con.SWP_SHOWWINDOW)
return True
def find_and_pin(process_names):
"""查找指定进程名的主窗口并置顶"""
pinned = 0
def enum_callback(hwnd, _):
nonlocal pinned
pname = get_process_name(hwnd)
if pname and pname in process_names:
if is_valid_main_window(hwnd):
if set_topmost(hwnd):
title = win32gui.GetWindowText(hwnd)
print(f"✅ 已置顶: {title} (进程: {pname}, HWND={hwnd})")
pinned += 1
return True
win32gui.EnumWindows(enum_callback, None)
return pinned
if __name__ == "__main__":
# 目标进程名(小写)
targets = ["qq.exe", "weixin.exe"]
print("正在查找 QQ / VX窗口...")
count = find_and_pin(targets)
if count == 0:
print("❌ 未找到 QQ 或VX的主窗口。请确保程序正在运行且窗口没有被最小化到系统托盘。")
else:
print(f"操作完成,共置顶 {count} 个窗口。")
input("按回车键退出...")
|