c# - 尝试从 user32.dll 的 GetWindowText() 读取窗口时发生类型为 'System.ExecutionEngineException' 的未处理异常

标签 c# user32

在我的应用程序中,我正在读取同一进程的窗口文本。我正在使用 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/

相关文章:

c# - 带有键和值列表的字典

c# - 使共享库可用于多个应用程序的最佳方法是什么?

c# - 定义构造函数签名的接口(interface)?

c# - 当外部应用程序的窗口移动时移动窗口

javascript - Node ffi Rect 类型

c++ - 如何恢复默认图标? (WinXP 和 Win7)

c# - 不应单击以前的窗体 [C#]

c# - 如何以及是否建立复合 View ?

c# - 使用 RegisterHotKey 通过 Numpad 注册热键

winapi - 在 Win32 上创建新窗口时如何得到通知?