在win32上使用python和ctypes获取列表框内容时遇到的问题
我想用Python和ctypes来获取一个列表框的内容。
item_count = ctypes.windll.user32.SendMessageA(hwnd, win32con.LB_GETCOUNT, 0, 0)
items = []
for i in xrange(item_count):
text_len = ctypes.windll.user32.SendMessageA(hwnd, win32con.LB_GETTEXTLEN, i, 0)
buffer = ctypes.create_string_buffer("", text_len+1)
ctypes.windll.user32.SendMessageA(hwnd, win32con.LB_GETTEXT, i, buffer)
items.append(buffer.value)
print items
我得到的项目数量是对的,但文本内容不对。所有的文本长度都是4,而文本的值像是'0\xd9\xee\x02\x90'这样的。
我尝试使用一个unicode缓冲区,结果也差不多。
我找不到我的错误。有没有什么想法?
2 个回答
0
看起来你需要使用一个紧凑的结构来存放结果。我在网上找到一个例子,也许这个对你有帮助:
http://www.brunningonline.net/simon/blog/archives/winGuiAuto.py.html
# Programmer : Simon Brunning - simon@brunningonline.net
# Date : 25 June 2003
def _getMultipleWindowValues(hwnd, getCountMessage, getValueMessage):
'''A common pattern in the Win32 API is that in order to retrieve a
series of values, you use one message to get a count of available
items, and another to retrieve them. This internal utility function
performs the common processing for this pattern.
Arguments:
hwnd Window handle for the window for which items should be
retrieved.
getCountMessage Item count message.
getValueMessage Value retrieval message.
Returns: Retrieved items.'''
result = []
VALUE_LENGTH = 256
bufferlength_int = struct.pack('i', VALUE_LENGTH) # This is a C style int.
valuecount = win32gui.SendMessage(hwnd, getCountMessage, 0, 0)
for itemIndex in range(valuecount):
valuebuffer = array.array('c',
bufferlength_int +
" " * (VALUE_LENGTH - len(bufferlength_int)))
valueLength = win32gui.SendMessage(hwnd,
getValueMessage,
itemIndex,
valuebuffer)
result.append(valuebuffer.tostring()[:valueLength])
return result
def getListboxItems(hwnd):
'''Returns the items in a list box control.
Arguments:
hwnd Window handle for the list box.
Returns: List box items.
Usage example: TODO
'''
return _getMultipleWindowValues(hwnd,
getCountMessage=win32con.LB_GETCOUNT,
getValueMessage=win32con.LB_GETTEXT)
1
如果你正在处理的列表框是由自己绘制的,那么下面这段来自于LB_GETTEXT的说明可能对你有帮助:
如果你创建列表框时使用了自绘样式,但没有使用LBS_HASSTRINGS样式,那么lParam参数指向的缓冲区将会接收到与该项目相关联的值(也就是项目数据)。
你收到的四个字节看起来确实像是一个指针,这通常是存储在每个项目数据中的一种典型值。