You need to enable JavaScript to run this app. 不使用Python win32gui获取当前前台窗口的方法有哪些?
优惠活动
大模型
产品
解决方案
定价
更多

不使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 16:27:05