win32gui get the current active application name

前端 未结 2 1206
你的背包
你的背包 2021-02-15 15:51

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.



        
相关标签:
2条回答
  • 2021-02-15 15:56

    Install WMI package first (and pywin32 of cause):

    pip install wmi
    

    Then:

    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 讨论(0)
  • 2021-02-15 16:07

    Think this will do the trick

    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()
    

    assuming you have installed psutil and win32 modules

    Run this program to get a better understanding

    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()
    
    0 讨论(0)
提交回复
热议问题