Python WM_GETTEXT返回以null分隔的文本

Python WM_GETTEXT返回以null分隔的文本,python,win32gui,Python,Win32gui,为什么它返回以null分隔的字符串?当我尝试buff[:length]时,由于空值,我有一半的字符串 import time import win32gui import win32con while True: time.sleep(1) buf = win32gui.PyMakeBuffer(255) window = win32gui.GetForegroundWindow() title = win32gui.GetWindowText(window)

为什么它返回以null分隔的字符串?当我尝试buff[:length]时,由于空值,我有一半的字符串

import time
import win32gui
import win32con

while True:
    time.sleep(1)
    buf = win32gui.PyMakeBuffer(255)
    window = win32gui.GetForegroundWindow()
    title = win32gui.GetWindowText(window)
    control = win32gui.FindWindowEx(window, 0, 'Edit', None)
    length = win32gui.SendMessage(control, win32con.WM_GETTEXT, 255, buf)
    result = buf[:length]
    print('Title: ', win32gui.GetWindowText(window))
    print(str(buf[:length*2], "UTF_8")
编辑:


代码按照我希望的那样工作,但我不确定它是否正确编写

您从Win32 API得到的是UTF-16字符串。每个字符都是16位,所以当作为字节数组查看时,每个ascii之间似乎有一个空字节

这是解释该字符串的正确方法:

result = buf.tobytes()[:length*2:2]
print(result.decode("UTF-8"))

您的解决方案能够使用utf-8解码,因为您跳过了所有空字符。这很好,但会产生奇怪的结果,并且在编辑控件中键入unicode字符时可能会引发异常。

使用您的代码,我得到了以下错误AttributeError:“memoryview”对象没有“decode”编辑属性:我使用了buf.tobytes.decodeUTF-16,它可以工作我使用的是python 3。我怀疑您使用的是python 2。很高兴它对你有用。
result = buf.tobytes()[:length*2:2]
print(result.decode("UTF-8"))
length = win32gui.SendMessage(control, win32con.WM_GETTEXT, 255, buf)
result = buf[0:length*2]
text = result.decode("utf-16")