简体   繁体   中英

C# A buffer overrun has occurred

A buffer overrun has occurred in MyApp.exe which has corrupted the program's internal state.

I've tried a few things but can't figure out what's causing the above in 1/50 calls, probably something obvious, it's a lot to guess at.

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

Thanks in advance.

You are not pre-allocating the buffer in the StringBuilder .

This line:

StringBuilder a = new StringBuilder();

Should be:

StringBuilder a = new StringBuilder(256);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM