Search code examples
c#winapipinvoke

GetWindowText in c# returns a rectangles instead of text


I have code like this:

IntPtr hwndGetValue = new IntPtr(67904);
List<IntPtr> windows = GetChildWindows(hwndGetValue);

int textLength = GetWindowTextLength(windows[0]);
StringBuilder outText = new StringBuilder(textLength + 1);
int a = GetWindowText(windows[0], outText, outText.Capacity);

in windows I have 49 pointers. Windows[0] have text which I can see in Spy++ but method GetWindowText return in outText rectangles instead of this text. I get {慬潹瑵潃瑮潲ㅬ} (in Visual and notepad this chinese signs are displayed as rectangles. I have something wrong with encoding ?

Thanks


Solution

  • These symptoms indicate that you are calling the ANSI version of GetWindowText but interpreting the returned value as Unicode.

    The solution is to make sure you call the Unicode version of GetWindowText instead. Do this by specifying Charset=Charset.Unicode in your DllImport.

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