9

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

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
4

2 回答 2

8

首先安装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
于 2013-02-20T06:15:07.547 回答
4

认为这会成功

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()
于 2017-12-22T06:20:34.740 回答