How to get the length of the window class name so that I know how big the buffer will be allocated?

How do I get the length of a class name in advance so that I can pass it to a parameter nMaxCountin GetClassName()? something like a WM_GETTEXTLENGTHmessage that exists for controls, or does the window class name have a fixed size limit? if so, what is this value?

My goal is the exact size of the passage, not the redistribution method (call GetClassName()until it returns a size smaller than its buffer).

My current implementation (without redistribution method):

[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);

string GetWindowClass(IntPtr hWnd)
{
    const int size = 256;
    StringBuilder buffer = new StringBuilder(size + 1);

    if (GetClassName(hWnd, buffer, size) == 0)
        Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());

    return buffer.ToString();
}
+4
source share
1 answer

256 . (. lpszClassName WNDCLASSEX). !

, . try-double-retry :

  • , , .
  • . , - .
  • , , , 2.

:

[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern int GetClassNameW(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);

string GetWindowClass(IntPtr hWnd)
{
    string className = String.Empty;
    int length = 10; // deliberately small so you can 
                     // see the algorithm iterate several times. 
    StringBuilder sb = new StringBuilder(length);
    while (length < 1024)
    {
        int cchClassNameLength = GetClassNameW(hWnd, sb, length);
        if (cchClassNameLength == 0)
        {
            throw new Win32Exception(Marshal.GetLastWin32Error());
        }
        else if (cchClassNameLength < length - 1) // -1 for null terminator
        {
            className = sb.ToString();
            break;
        }
        else length *= 2;
    }
    return className;
}

( , .)

+3

All Articles