win32gui获取当前活动的应用程序名称

时间:2013-01-18 07:48:42

标签: python windows win32gui

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

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

以上代码段有效。我没有尝试获取活动窗口的应用程序名称(Foreground Window

我的问题是:

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

修改

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

calc.exe
chrome.exe

2 个答案:

答案 0 :(得分:5)

首先安装WMI包(原因pywin32):

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

答案 1 :(得分:0)

认为这样可以解决问题

import psutil, win32process, win32gui, time
def active_window_process_name():
    pid = win32process.GetWindowThreadProcessId(win32gui.GetForegroundWindow()) #This produces a list of PIDs active window relates to
    print(psutil.Process(pid[-1]).name()) #pid[-1] is the most likely to survive last longer


time.sleep(3) #click on a window you like and wait 3 seconds 
active_window_process_name()

假设您已安装psutilwin32个模块

运行此程序以更好地理解

import threading, win32gui, win32process, psutil
from tkinter import *
root = Tk()
s = StringVar()
def active_window_process_name():
    try:
        pid = win32process.GetWindowThreadProcessId(win32gui.GetForegroundWindow())
        return(psutil.Process(pid[-1]).name())
    except:
        pass
def to_label():
    global s
    while True:
        s.set(active_window_process_name())
    return

Label(root,textvariable=s).pack()
if __name__ == "__main__":
    t = threading.Thread(target = to_label)
    t.start()
    root.mainloop()