2013-01-18 174 views
3

我只是在學習python,而我是相對性的新手。 我創建了以下腳本,它將獲取當前活動的窗口標題並將其打印到窗口。win32gui獲取當前活動的應用程序名稱

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 
+0

您需要定義你所說的「應用程序名稱」 –

+0

@DavidHeffernan更新的問題是什麼意思。 –

+0

這還不完全清楚。您是否正在尋找擁有該窗口的可執行文件的VERSIONINFO資源中包含的名稱? –

回答

3

安裝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 
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() 
相關問題