在我的应用程序中,我正在读取同一进程的窗口文本。我正在使用 User32.dll 的 GetWindowText。但是当它尝试调用该方法时,我收到异常“aaaa.exe 中发生类型为‘System.ExecutionEngineException’的未处理异常”。我在哪里可以看到确切的错误。以及为什么我得到这个异常(exception)。
我的代码如下。
[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
}
}
最佳答案
您收到此异常是因为您的 GetWindowText() 调用损坏了垃圾收集堆。当您传递字符串而不是 StringBuilder 或忘记初始化 StringBuilder 时,这很容易做到。
正确的方法:
[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();
//...
}
关于c# - 尝试从 user32.dll 的 GetWindowText() 读取窗口时发生类型为 'System.ExecutionEngineException' 的未处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2013310/