在Python中使用Ctypes可以获得记事本窗口的位置吗?
Python 3.8, OS: Windows 10.我试过这段代码,但它没有给出窗口的位置:
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)它分别给出了以下输出:
<ctypes.wintypes.RECT object at 0x0000029358dc05c0>
1发布于 2021-01-05 12:50:07
wintypes.RECT没有实现__repr__,所以它显示一个通用的对象/地址描述。您可以打印各个字段:
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或者,您可以在子类中定义__repr__。下面是一个经过完全类型检查和错误检查的版本:
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)https://stackoverflow.com/questions/65559197
复制相似问题