tags:

views:

238

answers:

2

In my application, I am reading the text of a window for the same process. I am using GetWindowText of User32.dll. But when it tries to call the method, I am getting the exception "An unhandled exception of type 'System.ExecutionEngineException' occurred in aaaa.exe". Where can I see the exact error. And why I am getting this exception.

My code is as below.

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

EnumDelegate enumfunc = new EnumDelegate(EnumWindowsProc);

private bool EnumWindowsProc(IntPtr win, int lParam)
{
    StringBuilder sb = new StringBuilder();
    GetWindowText(win, sb, 100);
    if (sb.Length > 0)
    {
        // do something
    }
}
+5  A: 

You are getting this exception because your GetWindowText() call corrupted the garbage collected heap. Easy to do when you pass a string instead of a StringBuilder or forget to initialize the StringBuilder.

The Right Way:

  [DllImport("user32.dll", CharSet = CharSet.Unicode)]
  private static extern bool GetWindowText(IntPtr hWnd, StringBuilder buffer, int buflen);
...
  var sb = new StringBuilder(666);
  if (GetWindowText(handle, sb, sb.Capacity)) {
    string txt = sb.ToString();
    //...
  }
Hans Passant
I am using the string builder and initialized it also. Only change is I am using charset as CharSet.Auto. Will it be a problem?
AvidProgrammer
Do you have a reference for your last statement? I've been using GetWindowText successfully to retrieve the caption of out-of-proc HWNDs and according to the remarks section here (http://msdn.microsoft.com/en-us/library/ms633520%28VS.85%29.aspx) this should not be a problem either.
0xA3
Just this one: *This function cannot retrieve the text of an edit control in another application.* I'll update my post, thanks.
Hans Passant
@Avid: post your code.
Hans Passant
@nobugz: Sorry, I was missing that part from the documentation. I was only using GetWindowText to get the caption of other application's main windows which is no problem. Thanks for the hint!
0xA3
A: 

You have no idea how much this article has helped me, thanks!

TnX