2010-07-29 91 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