Search code examples
pythonctypes

How to know window ClassName length?


I can get window title with this function:

import ctypes
from ctypes import wintypes
from collections import namedtuple
user32 = ctypes.WinDLL('user32', use_last_error=True)

def get_title(hWnd, lParam):
    pid = wintypes.DWORD()
    length = user32.GetWindowTextLengthW(hWnd) + 1
    title = ctypes.create_unicode_buffer(length)
    user32.GetWindowTextW(hWnd, title, length)
    return title.value

I can get ClassName using user32.GetClassNameW, but which function can be an alternative to GetWindowTextLengthW, that gives length of ClassName?


Solution

  • The class name is a maximum of 256 characters as per the documentation for WNDCLASSEX, so you can just give it a buffer of 257 characters (one extra for the terminator as per GetClassName). When dealing with buffers that small there's no point taking extra steps to save a few bytes in getting the exact buffer size.