Skip to content

Instantly share code, notes, and snippets.

@ra101
Created March 29, 2023 11:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ra101/f9baa2f0bf2d16395088f695eed3e638 to your computer and use it in GitHub Desktop.
Save ra101/f9baa2f0bf2d16395088f695eed3e638 to your computer and use it in GitHub Desktop.
get exe name of foreground window
from os.path import basename as get_base_name
from ctypes import wintypes, windll, create_unicode_buffer, byref
def getActiveWindowExe():
# PROCESS_QUERY_INFORMATION, PROCESS_VM_READ, BUF_LEN = 0x0400, 0x0010, 260
hwnd, pid = windll.user32.GetForegroundWindow(), wintypes.DWORD()
tid = windll.user32.GetWindowThreadProcessId(hwnd, byref(pid))
handle = windll.kernel32.OpenProcess(0x0400 | 0x0010, False, pid)
buf = create_unicode_buffer(260)
windll.psapi.GetModuleFileNameExW(handle, 0, buf, 260)
exe_name = get_base_name(buf.value)
windll.kernel32.CloseHandle(handle)
return exe_name if exe_name else None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment