使用 ctypes 获取可用工作区

Get usable work area with ctypes

我的目标是在 ctypes 和 user32.dll (SystemParametersInfo) 的帮助下获得 python 中的可用工作区。嗯,我是第二次用ctypes,不是很懂。解释我做错了什么会很棒。谢谢

import ctypes

SPI_GETWORKAREA = 48
SPI = ctypes.windll.user32.SystemParametersInfoA

class RECT(ctypes.Structure):
    _fields_ = [
        ('left', ctypes.c_long),
        ('top', ctypes.c_long),
        ('right', ctypes.c_long),
        ('bottom', ctypes.c_long)
    ]

SPI.restype = ctypes.POINTER(RECT)
SPI.argtypes = [ctypes.c_uint, ctypes.c_uint, ctypes.c_uint]
result = SPI(SPI_GETWORKAREA, 0, 0)
print(result)

您有一些错误:

  • Python 3 使用 unicode 字符串,因此请改用 SystemParametersInfoW(尽管对于此特定函数,它可能会以任何一种方式工作)。
  • 函数调用需要 4 个参数,而不是 3 个。
  • return类型是布尔值,不是矩形结构。
  • 您需要访问函数调用后传入的相同 RECT 结构。函数调用就地修改它。

结合这些更改代码对我有用:

import ctypes


SPI_GETWORKAREA = 48
SPI = ctypes.windll.user32.SystemParametersInfoW


class RECT(ctypes.Structure):
    _fields_ = [
        ('left', ctypes.c_long),
        ('top', ctypes.c_long),
        ('right', ctypes.c_long),
        ('bottom', ctypes.c_long)
    ]


SPI.restype = ctypes.c_bool
SPI.argtypes = [
    ctypes.c_uint,
    ctypes.c_uint,
    ctypes.POINTER(RECT),
    ctypes.c_uint
]

rect = RECT()

result = SPI(
    SPI_GETWORKAREA,
    0, 
    ctypes.byref(rect),
    0
)
if result:
    print('it worked!')
    print(rect.left)
    print(rect.top)
    print(rect.right)
    print(rect.bottom)