N
N
Nikolai Pavlov2017-03-30 14:08:50
Python
Nikolai Pavlov, 2017-03-30 14:08:50

Why is the Cyrillic string in create_string_buffer distorted?

Good day.
Tell me, what could be the problem, there is such a code in Python:

import time
from ctypes import *
from win32con import *
from ctypes.wintypes import HWND, DWORD
from win32gui import GetForegroundWindow, SendMessage
from win32process import GetWindowThreadProcessId

GetGUIThreadInfo = windll.user32.GetGUIThreadInfo

class RECT(Structure):
    _fields_ = [("left", c_ulong),
                ("top", c_ulong),
                ("right", c_ulong),
                ("bottom", c_ulong)]

class GUITHREADINFO(Structure):
    _fields_ = [("cbSize", DWORD),
                ("flags", DWORD),
                ("hwndActive", HWND),
                ("hwndFocus", HWND),
                ("hwndCapture", HWND),
                ("hwndMenuOwner", HWND),
                ("hwndMoveSize", HWND),
                ("hwndCaret", HWND),
                ("rcCaret", RECT)]

time.sleep(5)
PID = GetWindowThreadProcessId(GetForegroundWindow())
lpgui = GUITHREADINFO()
lpgui.cbSize = sizeof(GUITHREADINFO)
GetGUIThreadInfo(PID[0], pointer(lpgui))

textMaxSize = 32
text = create_string_buffer(textMaxSize)
SendMessage(lpgui.hwndFocus, WM_GETTEXT, textMaxSize, text)
print(text.value)

when you run it on Python 2.7 x32 and activate, for example, a notepad with the text 'Hellow(Hello)' in the buffer, the correct text, when you run it on Python 3.6 x64, the line is distorted, I get this b'H', it is written to text.raw like this this bytes value: b'H\x00e\x00l\x00l\x00o\x00w\x00(\x00\x1f\[email protected]\x048\x042\x045\x04B\x04)\x00\x00\x00\x00\x00' when it is not possible to correctly convert this set of bytes. Help me to understand.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikolay Pavlov, 2017-03-31
@PavlovNik

I figured out what the problem is, text.value encodes a string in utf-8 by default, and SendMessage writes a character in two bytes to the buffer, i.e. if you recode the buffer yourself like this: then everything is displayed correctly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question