简体   繁体   中英

Python Memorybuffer pywin32

I got some code:

    def get_text(self, id):
        edit_hwnd = win32gui.GetDlgItem(self.hwnd, id)  # 获取窗口句柄
        time.sleep(0.2)
        self.edit_hwnd = edit_hwnd
        length = win32api.SendMessage(
             edit_hwnd, win32con.WM_GETTEXTLENGTH) + 1  # 获取窗体内容长度
        buf = win32gui.PyMakeBuffer(length)  # 准备buffer对象作为容器
        win32gui.SendMessage(edit_hwnd, win32con.WM_GETTEXT,
                         length, buf)  # 获取窗体内容放入容器
        try:
            address, length = win32gui.PyGetBufferAddressAndLen(buf)  # 获取容器的内存地址
        except ValueError:
            print('error')
            return
        text = win32gui.PyGetString(address, length)  # 取得字符串
        buf.release()
        del buf
        return text

This function for get string at windows.I need to while this func to always get this value.When the value changed,i do something.But now when i done this while,my program exit with error code C000005.How can i fix it.

buf.release()
del buf

It's i added when i found this problem.It look like does't work.

The messages WM_GETTEXTLENGTH returns the length of the text in characters ( excluding the terminating null character) and the maximum buffer length given to WM_GETTEXT also is based on characters ( including the terminating null character).

A character in the NT-based Windows systems is encoded in a double-byte character set (DBCS), meaning two bytes per character.

The function win32gui.PyMakeBuffer(length) returns a buffer of length bytes .

So if length is the return value of WM_GETTEXTLENGTH , the reserved buffer should be length * 2 + 2 bytes long and the maximum buffer length given to WM_GETTEXT should be length + 1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM