Skip to content

Instantly share code, notes, and snippets.

@jerblack
Last active May 2, 2023 13:26
Show Gist options
  • Save jerblack/2b294916bd46eac13da7d8da48fcf4ab to your computer and use it in GitHub Desktop.
Save jerblack/2b294916bd46eac13da7d8da48fcf4ab to your computer and use it in GitHub Desktop.
Find and move windows in Windows with ctypes and user32 in Python
import ctypes
user32 = ctypes.windll.user32
# get screen resolution of primary monitor
res = (user32.GetSystemMetrics(0), user32.GetSystemMetrics(1))
# res is (2293, 960) for 3440x1440 display at 150% scaling
user32.SetProcessDPIAware()
res = (user32.GetSystemMetrics(0), user32.GetSystemMetrics(1))
# res is now (3440, 1440) for 3440x1440 display at 150% scaling
# get handle for Notepad window
# non-zero value for handle should mean it found a window that matches
handle = user32.FindWindowW(u'Notepad', None)
# or
handle = user32.FindWindowW(None, u'Untitled - Notepad')
# meaning of 2nd parameter defined here
# https://msdn.microsoft.com/en-us/library/windows/desktop/ms633548(v=vs.85).aspx
# minimize window using handle
user32.ShowWindow(handle, 6)
# maximize window using handle
user32.ShowWindow(handle, 9)
# move window using handle
# MoveWindow(handle, x, y, height, width, repaint(bool))
user32.MoveWindow(handle, 100, 100, 400, 400, True)
@ChathuraGH
Copy link

Thanks for sharing this code. It helped me.

@THEGOLDENPRO
Copy link

Also thanks for sharing this code. Really appreciate it.

@crisleo94
Copy link

Hey, thanks so much for the snippet, clearly what I was looking for, I have one question though, is it possible to detect any other programs besides the ones included with Windows? I've been trying to detect VSCode and Firefox, but the result is always 0

@jerblack
Copy link
Author

This should have no problem finding a window for which there is only one executable. It doesn't have anything to do with it being included in Windows. Both of the examples you listed are multiprocess applications though, so opening VScode once ends up opening several instances of code.exe, only one of which will have a valid window handle. You will need to iterate through all of those instances of code.exe to find the one that has a window handle (you can see this by opening the Sysinternals tool, Process Explorer and adding the Window Title column).

This page shows how you can enumerate all open Windows and get their titles.
https://sjohannes.wordpress.com/2012/03/23/win32-python-getting-all-window-titles/

@crisleo94
Copy link

Exactly what I did, it was my mistake anyways as I was iterating through the opened windows I needed the second option of the FindWindowW, thanks!!

@shakilofficial0
Copy link

thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment