Skip to content Skip to sidebar Skip to footer

Wm_gettext Returns Text Separated With Nulls

import time import win32gui import win32con while True: time.sleep(1) buf = win32gui.PyMakeBuffer(255) window = win32gui.GetForegroundWindow() title = win32gui.Get

Solution 1:

What you are getting back from the Win32 API is a UTF-16 string. Each character is 16-bits, so that's why it appears as if a null byte is in between each ascii when viewed as a byte array.

This is the correct way to interpret that string:

length = win32gui.SendMessage(control, win32con.WM_GETTEXT, 255, buf)
result = buf[0:length*2]
text = result.decode("utf-16")

Your solution manages to work with a utf-8 decode because you are skipping over all the null chars. That works fine, but will generate weird results (and possibly throw an exception) as soon as unicode characters are typed typed into that edit control.

Post a Comment for "Wm_gettext Returns Text Separated With Nulls"