相关文章推荐
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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.

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

The above code snippet works. I am now trying to get the application name for the active window (Foreground Window)

My question is:

  • How do you get the foreground active windows application name in python?
  • For example: If a user switches from a Calculator (calc.exe) to Google Chrome (chrome.exe) I want to see what the application that they switched to is called. The problem with the title is that not all applications prefix the title with the application name. For example google chrome puts the page title as the window title. I want to know what the application that the user switched to is called.

    calc.exe
    chrome.exe
                    That's still not totally clear. Are you looking for the name contained in the VERSIONINFO resource of the executable file that owns the Window?
    – David Heffernan
                    Jan 18, 2013 at 11:49
                    If you want to find the name of the executable file running, try using the psutil library. I have successfully listed through processes and got the executable names in this technique. The only problem is that it may be difficult to get the foreground process, or correspond the process with the header of the foreground window you found.
    – trevorKirkby
                    Jan 2, 2014 at 19:57
        """Get applicatin path given hwnd."""
            _, 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."""
            _, 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
    
    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():
            pid = win32process.GetWindowThreadProcessId(win32gui.GetForegroundWindow())
            return(psutil.Process(pid[-1]).name())
        except:
    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()
            

    Thanks for contributing an answer to Stack Overflow!

    • Please be sure to answer the question. Provide details and share your research!

    But avoid

    • Asking for help, clarification, or responding to other answers.
    • Making statements based on opinion; back them up with references or personal experience.

    To learn more, see our tips on writing great answers.

     
    推荐文章