不使用Python win32gui获取当前前台窗口的方法有哪些?
获取当前前台窗口的其他实现方法
原生API直接调用(无需依赖win32gui封装)
- 调用user32.dll原生接口:Windows前台窗口的获取能力本质是系统user32.dll提供的,可通过任意支持动态链接库调用的语言直接调用对应接口,无需依赖pywin32的win32gui封装。以Python的ctypes库为例,实现代码如下:
import ctypes from ctypes import wintypes # 加载user32.dll user32 = ctypes.WinDLL('user32', use_last_error=True) # 声明函数返回值、参数类型 user32.GetForegroundWindow.restype = wintypes.HWND user32.GetWindowTextW.argtypes = [wintypes.HWND, wintypes.LPWSTR, ctypes.c_int] # 获取前台窗口句柄 hwnd = user32.GetForegroundWindow() # 读取窗口标题 buffer_length = 512 text_buffer = ctypes.create_unicode_buffer(buffer_length) user32.GetWindowTextW(hwnd, text_buffer, buffer_length) window_title = text_buffer.value
其他Python第三方库实现
- pygetwindow库:专门用于窗口操作的轻量跨平台库,Windows环境下可直接调用接口获取前台窗口:
import pygetwindow as gw active_window = gw.getActiveWindow() # 获取标题使用active_window.title,获取窗口句柄使用active_window._hWnd
- pyautogui库:UI自动化常用库自带活动窗口获取能力,实现代码如下:
import pyautogui active_window = pyautogui.getActiveWindow() print(active_window.title)
系统脚本方案(无需安装Python第三方库)
- PowerShell脚本实现:直接通过PowerShell调用系统接口,不需要额外安装依赖,命令如下:
Add-Type @" using System; using System.Runtime.InteropServices; public class Win32 { [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] public static extern int GetWindowText(IntPtr hWnd, System.Text.StringBuilder text, int count); } "@ $hwnd = [Win32]::GetForegroundWindow() $titleBuilder = New-Object System.Text.StringBuilder 512 [Win32]::GetWindowText($hwnd, $titleBuilder, 512) | Out-Null $titleBuilder.ToString()
以上所有方案底层均依赖Windows系统user32.dll的标准接口,仅上层封装逻辑不同,可根据自身使用场景选择。
内容的提问来源于stack exchange,提问作者Augurkenplukker12
相关产品推荐
相关产品推荐

