Ste*_*rst 5 python windows win32gui
我只是在学习python,而我是相对论的新手。我创建了以下脚本,该脚本将获取当前活动的Windows标题并将其打印到窗口中。
import win32gui
windowTile = "";
while ( True ) :
newWindowTile = win32gui.GetWindowText (win32gui.GetForegroundWindow());
if( newWindowTile != windowTile ) :
windowTile = newWindowTile ;
print( windowTile );
Run Code Online (Sandbox Code Playgroud)
上面的代码段有效。我没有尝试获取活动窗口(Foreground Window)的应用程序名称
我的问题是:
编辑
例如:如果用户从计算器(calc.exe)切换到Google Chrome(chrome.exe),我想查看他们切换到的应用程序被调用了。标题的问题在于,并非所有的应用程序都以应用程序名称作为标题的前缀。例如,谷歌浏览器将页面标题作为窗口标题。我想知道用户切换到哪个应用程序。
calc.exe
chrome.exe
Run Code Online (Sandbox Code Playgroud)
小智 5
WMI首先安装软件包(以及pywin32原因):
pip install wmi
Run Code Online (Sandbox Code Playgroud)
然后:
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
Run Code Online (Sandbox Code Playgroud)
认为这可以解决问题
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()
Run Code Online (Sandbox Code Playgroud)
假设您已经安装psutil了win32模块
运行这个程序以获得更好的理解
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()
Run Code Online (Sandbox Code Playgroud)