oduncu90
oduncu90

Reputation: 45

Ctypes Get Window Location

Is it possible to get the Notepad window location by using Ctypes in Python?

Python 3.8, OS: Windows 10.

I have tried this code but it did not give location of the window:

import ctypes
user32 = ctypes.windll.user32
handle = user32.FindWindowW(None, u'test - Notepad')
rect = ctypes.wintypes.RECT()
ff=ctypes.windll.user32.GetWindowRect(handle, ctypes.pointer(rect))
print(rect)
print(ff)

It gives the following output respectively:

<ctypes.wintypes.RECT object at 0x0000029358dc05c0>
1

Upvotes: 2

Views: 2188

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 177600

The wintypes.RECT doesn't implement __repr__ so it displays a generic object/address description. You can print the individual fields:

import ctypes
from ctypes import wintypes
user32 = ctypes.windll.user32
handle = user32.FindWindowW(None, 'Untitled - Notepad')
rect = wintypes.RECT()
ff=ctypes.windll.user32.GetWindowRect(handle, ctypes.pointer(rect))
print(rect.left,rect.top,rect.right,rect.bottom)
print(ff)
153 188 1214 1157
1

Or you can define __repr__ in a subclass. Here's a fully type-checked and error-checked version:

import ctypes
from ctypes import wintypes as w

def errcheck(result,func,args):
    if result is None or result == 0:
        raise ctypes.WinError(ctypes.get_last_error())
    return result

# wintypes.RECT doesn't know how to display itself,
# so make a subclass that does.
class Rect(w.RECT):
    def __repr__(self):
        return f'Rect(left={self.left},top={self.top},right={self.right},bottom={self.bottom})'

user32 = ctypes.WinDLL('user32',use_last_error=True)
user32.FindWindowW.argtypes = w.LPCWSTR,w.LPCWSTR
user32.FindWindowW.restype = w.HWND
user32.GetWindowRect.argtypes = w.HWND,ctypes.POINTER(Rect)
user32.GetWindowRect.restype = w.BOOL
user32.GetWindowRect.errcheck = errcheck

if __name__ == '__main__':
    handle = user32.FindWindowW(None, 'Untitled - Notepad')
    if handle:
        rect = Rect()
        user32.GetWindowRect(handle,ctypes.byref(rect))
        print(rect)
    else:
        print('window not found')
Rect(left=153,top=188,right=1214,bottom=1157)

Upvotes: 3

Related Questions