首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Ctypes获取窗口位置

Ctypes获取窗口位置
EN

Stack Overflow用户
提问于 2021-01-04 15:43:16
回答 1查看 314关注 0票数 1

在Python中使用Ctypes可以获得记事本窗口的位置吗?

代码语言:javascript
复制
Python 3.8, OS: Windows 10.

我试过这段代码,但它没有给出窗口的位置:

代码语言:javascript
复制
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)

它分别给出了以下输出:

代码语言:javascript
复制
<ctypes.wintypes.RECT object at 0x0000029358dc05c0>
1
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-05 12:50:07

wintypes.RECT没有实现__repr__,所以它显示一个通用的对象/地址描述。您可以打印各个字段:

代码语言:javascript
复制
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)
代码语言:javascript
复制
153 188 1214 1157
1

或者,您可以在子类中定义__repr__。下面是一个经过完全类型检查和错误检查的版本:

代码语言:javascript
复制
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')
代码语言:javascript
复制
Rect(left=153,top=188,right=1214,bottom=1157)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65559197

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档