An unhandled exception of type 'System.ExecutionEngineException' occurring When trying to read window from GetWindowText() of user32.dll

流过昼夜 提交于 2019-12-11 02:52:31

问题


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
    }
}

回答1:


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();
    //...
  }


来源:https://stackoverflow.com/questions/2013310/an-unhandled-exception-of-type-system-executionengineexception-occurring-when

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!