Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetWindowText in c# returns a rectangles instead of text

Tags:

c#

pinvoke

winapi

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

like image 900
Robert Avatar asked Mar 02 '12 21:03

Robert


1 Answers

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);
like image 76
David Heffernan Avatar answered Nov 14 '22 23:11

David Heffernan