Monday, January 02, 2006

Getting the text of a window in .NET

I see this request come up often in CodeProject and on MS newsgroups. How can you get the text of a non-managed window. The easiest way is to go through the P/Invoke layer. Here's a sample.



public class Foo
{
[DllImport("user32.dll", CharSet=CharSet.Auto)]
private static extern uint GetWindowText(
IntPtr hwnd,
StringBuilder builder,
int maxCount);

public static string GetWindowText(IntPtr hwnd)
{
StringBuilder builder = new StringBuilder(256);
if ( 0 == GetWindowText(hwnd, builder, 256) )
{
throw new Exception("Error getting window text");
}
return builder.ToString();
}
}



There is one entry of note here. In the DllImport statement I set the CharSet to CharSet.Auto. The problem here is that the default is CharSet.Ansi which is not correct for most operating systems which run in Unicode. Whenever you're going to the OS layer through P/Invoke set this to CharSet.Auto.

0 Comments:

Post a Comment

<< Home