Python ctypes UnicodeEncodeError

408 Views Asked by At

I'm checking for an active window title every second, as follows:

import ctypes, time

GetForegroundWindow = ctypes.windll.user32.GetForegroundWindow
GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW
GetWindowText = ctypes.windll.user32.GetWindowTextW

while True:
    time.sleep(1)
    act_id = GetForegroundWindow()
    length = GetWindowTextLength(act_id)
    buff = ctypes.create_unicode_buffer(length + 1)
    GetWindowText(act_id, buff, length + 1)
    print(buff.value)

It works, but printing the title of some windows causes the following error:

UnicodeEncodeError: 'charmap' codec can't encode character '\u017d' in position
0: character maps to <undefined>

How should I solve this encoding error?

1

There are 1 best solutions below

1
On BEST ANSWER
import ctypes, time
GetForegroundWindow = ctypes.windll.user32.GetForegroundWindow
GetWindowTextLength = ctypes.windll.user32.GetWindowTextLengthW
GetWindowText = ctypes.windll.user32.GetWindowTextW
WriteConsoleW = ctypes.windll.kernel32.WriteConsoleW
STD_OUTPUT_HANDLE = - 11
outhandle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)

while True:
    time.sleep(1)
    act_id = GetForegroundWindow()
    length = GetWindowTextLength(act_id)
    buff = ctypes.create_unicode_buffer(length + 1)
    GetWindowText(act_id, buff, length + 1)
    chars_written = ctypes.c_int(0)
    title = buff.value + "\n"
    ctypes.windll.kernel32.WriteConsoleW(outhandle, title, len(title), ctypes.byref(chars_written), None)

This works well. Now for example 'č' is printed as 'c' and that is sufficient for me.