2010-07-29 100 views
0

我正在尝试使用TTM_GETTEXT通过SendMessage使用pywin32。问题是,应该存储文本的lparam的结构必须是TOOLINFO,这在MSDN中有详细记录,但在pywin32中没有对应文件。有没有办法使用python和pywin32创建相同的结构?将c中的结构转换为pywin32?

编辑:这里是代码我想出了使用​​。我为TOOLINFO做了一个Structure,创建了一个缓冲区从它传递到pywin32的SendMessage,然后将它转换回TOOLINFO​​Structure。唯一的问题是,它不工作:并没有被打印

# My TOOLINFO struct: 
class TOOLINFO(Structure): 
    _fields_ = [("cbSize", UINT), 
       ("uFlags", UINT), 
       ("hwnd", HWND), 
       ("uId", POINTER(UINT)), 
       ("rect", RECT), 
       ("hinst", HINSTANCE), 
       ("lpszText", LPWSTR), 
       ("lpReserved", c_void_p)] 

# send() definition from PythonInfo wiki FAQs 
def send(self): 
    return buffer(self)[:] 

ti = TOOLINFO() 
text = "" 
ti.cbSize = sizeof(ti) 
ti.lpszText = text     # buffer to store text in 
ti.uId = pointer(UINT(wnd))  # wnd is the handle of the tooltip 
ti.hwnd = w_wnd     # w_wnd is the handle of the window containing the tooltip 
ti.uFlags = commctrl.TTF_IDISHWND # specify that uId is the control handle 
ti_buffer = send(ti)    # convert to buffer for pywin32 

del(ti) 

win32gui.SendMessage(wnd, commctrl.TTM_GETTEXT, 256, ti_buffer) 

ti = TOOLINFO()    # create new TOOLINFO() to copy result to 

# copy result (according to linked article from Jeremy) 
memmove(addressof(ti), ti_buffer, sizeof(ti)) 

if ti.lpszText: 
    print ti.lpszText   # print any text recovered from the tooltip 

文字,但我认为它应该包含从我想提取工具提示文本。我如何使用​​有什么问题吗?我很确定我的wndw_wnd的值是正确的,所以我一定是做错了。

回答

1

这不是特别漂亮,但你可以使用struct模块包装领域与适当的字节顺序,对齐和填充一个字符串。这有点棘手,因为您必须使用正确顺序的相应基本数据类型以格式字符串定义结构。

您也可以使用ctypes的用于定义结构类型或也直接与的DLL接口(而不是使用pywin32)。 ctypes结构定义更接近C定义,所以你可能会更喜欢它。

如果您选择使用与pywin32沿着结构DEFS ctypes的,看看下面的线索,以如何将结构序列化到字符串:How to pack and unpack using ctypes (Structure <-> str)

+0

'ctypes'很好看,但我陷得太深pywin32已经可以切换。但结构模块看起来也不错。我可能会用'struct'方法。谢谢! – maranas 2010-07-30 09:30:28