Search code examples
pythonctypesactive-window

Python check if current window is file explorer (windows)


I am using this code to obtain current window

from typing import Optional
from ctypes import wintypes, windll, create_unicode_buffer

def getForegroundWindowTitle() -> Optional[str]:
    hWnd = windll.user32.GetForegroundWindow()
    length = windll.user32.GetWindowTextLengthW(hWnd)
    buf = create_unicode_buffer(length + 1)
    windll.user32.GetWindowTextW(hWnd, buf, length + 1) 
    return buf.value if buf.value else None 

print(getForegroundWindowTitle())
    
    output:
        Videos
        git
        Downloads
        Python check if current window is file explorer - Stack Overflow - Google Chrome

While google chrome tabs can be easily identified using this, problem is there's no way to know whether Videos, git, Downloads are windows folder (opened using file explorer).

So, is there a way to get the output in this format Videos - File Explorer ?
/ check whether the current window is a windows folder/file explorer window ?


Solution

  • From the same Question I modified the Code of Nuno Andre https://stackoverflow.com/a/56572696/2532695

    import ctypes
    from ctypes import wintypes
    import psutil
    
    user32 = ctypes.windll.user32
    
    h_wnd = user32.GetForegroundWindow()
    pid = wintypes.DWORD()
    user32.GetWindowThreadProcessId(h_wnd, ctypes.byref(pid))
    print(psutil.Process(pid.value).name())
    

    This one should do the trick, but you need psutil (pip install psutil). You should see something like "Explorer.exe" if the active Window is an Explorer-Window.