Skip to content

Instantly share code, notes, and snippets.

@ishikawash
Created May 11, 2021 12:52
Show Gist options
  • Save ishikawash/521966793233c1bfb7b320f8256876a5 to your computer and use it in GitHub Desktop.
Save ishikawash/521966793233c1bfb7b320f8256876a5 to your computer and use it in GitHub Desktop.
Activate window by process ID in Python
# ref: https://sjohannes.wordpress.com/tag/win32/
from __future__ import print_function
import ctypes
from ctypes import windll
import sys
Win32 = windll.user32
EnumWindowsProc = ctypes.WINFUNCTYPE(ctypes.c_int, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int))
def activate_window_by_pid(pid):
def activate_window(hwnd):
target_pid = ctypes.c_ulong()
Win32.GetWindowThreadProcessId(hwnd, ctypes.byref(target_pid))
if pid == target_pid.value:
Win32.SetForegroundWindow(hwnd)
Win32.BringWindowToTop(hwnd)
return True
else:
return False
def each_window(hwnd, _):
if activate_window(hwnd):
print("Activate: {0}".format(pid))
return 1
proc = EnumWindowsProc(each_window)
Win32.EnumWindows(proc, 0)
def main():
target_pids = [int(arg) for arg in sys.argv[1:]]
for pid in target_pids:
activate_window_by_pid(pid)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment