You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python通过进程名获取对应运行应用的正式显示名称

通过进程可执行名获取应用正式显示名称的实现方案

你当前的代码仅能获取进程的exe文件名,要拿到pycharm64.exe对应PyCharm、chrome.exe对应Google Chrome这类正式显示名,需要读取exe文件的版本信息中的产品名称字段。

  • 需提前安装依赖库:pip install wmi pywin32

完整可运行代码

import wmi
import win32process
import win32gui
import win32api
import time

c = wmi.WMI()

def get_app_display_name(hwnd):
    """根据窗口句柄获取对应应用的正式显示名称"""
    try:
        # 获取窗口对应的进程ID
        _, pid = win32process.GetWindowThreadProcessId(hwnd)
        # 查询进程的exe文件名和全路径
        for p in c.query(f'SELECT Name, ExecutablePath FROM Win32_Process WHERE ProcessId = {pid}'):
            exe_name = p.Name
            exe_path = p.ExecutablePath
            if not exe_path:
                return exe_name
            # 读取exe的版本信息
            info = win32api.GetFileVersionInfo(exe_path, '\\')
            lang, codepage = win32api.GetFileVersionInfo(exe_path, '\\VarFileInfo\\Translation')[0]
            # 读取产品名称字段
            product_name = win32api.GetFileVersionInfo(exe_path, f'\\StringFileInfo\\{lang:04x}{codepage:04x}\\ProductName')
            return product_name.strip() if product_name else exe_name
    except Exception:
        # 异常情况兜底返回
        return None

while True:
    time.sleep(3)
    foreground_hwnd = win32gui.GetForegroundWindow()
    print(get_app_display_name(foreground_hwnd))

部分特殊系统进程、绿色软件可能没有写入版本信息,此时会兜底返回exe文件名。

内容的提问来源于stack exchange,提问作者Mohamed Gamal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 13:06:03