本文介绍了win32gui 获取当前活动的应用程序名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在学习 Python,而且我是相对论新手.我创建了以下脚本,它将获取当前活动的窗口标题并将其打印到窗口.

I am just learning python and I am relativity new to it.I created the following script that will get the current active windows title and print it to the window.

import win32gui
windowTile = "";
while ( True ) :
    newWindowTile = win32gui.GetWindowText (win32gui.GetForegroundWindow());
    if( newWindowTile != windowTile ) :
        windowTile = newWindowTile ;
        print( windowTile );

上面的代码片段有效.我现在正在尝试获取活动窗口的应用程序名称(Foreground Window)

The above code snippet works. I am now trying to get the application name for the active window (Foreground Window)

我的问题是:

  • 如何在python中获取前台活动窗口应用程序名称?

编辑

例如:如果用户从计算器 (calc.exe) 切换到 Google Chrome (chrome.exe),我想查看他们切换到的应用程序的名称.标题的问题在于并非所有应用程序都以应用程序名称作为标题的前缀.例如谷歌浏览器将页面标题作为窗口标题.我想知道用户切换到的应用程序叫什么.

For example: If a user switches from a Calculator (calc.exe) to Google Chrome (chrome.exe) I want to see what the application that they switched to is called. The problem with the title is that not all applications prefix the title with the application name. For example google chrome puts the page title as the window title. I want to know what the application that the user switched to is called.

calc.exe
chrome.exe

推荐答案

先安装WMI包(和pywin32的原因):

Install WMI package first (and pywin32 of cause):

pip install wmi

那么:

import win32process
import wmi


c = wmi.WMI()


def get_app_path(hwnd):
    """Get applicatin path given hwnd."""
    try:
        _, pid = win32process.GetWindowThreadProcessId(hwnd)
        for p in c.query('SELECT ExecutablePath FROM Win32_Process WHERE ProcessId = %s' % str(pid)):
            exe = p.ExecutablePath
            break
    except:
        return None
    else:
        return exe


def get_app_name(hwnd):
    """Get applicatin filename given hwnd."""
    try:
        _, pid = win32process.GetWindowThreadProcessId(hwnd)
        for p in c.query('SELECT Name FROM Win32_Process WHERE ProcessId = %s' % str(pid)):
            exe = p.Name
            break
    except:
        return None
    else:
        return exe

这篇关于win32gui 获取当前活动的应用程序名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 16:08