C# 发生了缓冲区溢出

C# A buffer overrun has occurred

本文关键字:溢出 缓冲区 发生了      更新时间:2023-10-16
A buffer overrun has occurred in MyApp.exe which has corrupted the program's internal state.

我已经尝试了一些方法,但无法弄清楚是什么导致了 1/50 次通话中的上述情况,可能是显而易见的,有很多猜测。

[DllImport("user32.dll")]
public static extern IntPtr GetTopWindow(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out UInt32 pid);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);
public static IntPtr GetProcessWindow(int processId)
{
    UInt32 pid = 0;
    UInt32 dwThreadId = 0;
    StringBuilder a = new StringBuilder();
    IntPtr hwnd = GetTopWindow(IntPtr.Zero);
    while(hwnd != null)
    {
        dwThreadId = GetWindowThreadProcessId(hwnd, out pid);
        GetWindowText(hwnd, a, 256);
        String name = a.ToString();
        if(pid == processId && name.Contains("[Window Name]"))
            return hwnd;
        hwnd = GetWindow(hwnd, 2);
    }
    return IntPtr.Zero;
}

提前谢谢。

您没有在StringBuilder中预先分配缓冲区。

这一行:

StringBuilder a = new StringBuilder();

应该是:

StringBuilder a = new StringBuilder(256);

尝试使用GetWindowTextLength API 调用定义的容量初始化StringBuilder