[Solved] Remove space left after console scrollbars in C#


Finally, after a lot of head-scratching, I think I’ve solved this issue. Firstly, I had to add some additional WinAPI methods:

[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr GetStdHandle(int nStdHandle);

[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GetConsoleScreenBufferInfoEx(
    IntPtr hConsoleOutput,
    ref ConsoleScreenBufferInfoEx ConsoleScreenBufferInfo);

[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetConsoleScreenBufferInfoEx(
    IntPtr hConsoleOutput,
    ref ConsoleScreenBufferInfoEx ConsoleScreenBufferInfoEx);

and structs:

[StructLayout(LayoutKind.Sequential)]
private struct ConsoleScreenBufferInfoEx
{
    public uint cbSize;
    public Coord dwSize;
    public Coord dwCursorPosition;
    public short wAttributes;
    public SmallRect srWindow;
    public Coord dwMaximumWindowSize;
    public ushort wPopupAttributes;
    public bool bFullscreenSupported;

    public Colorref black, darkBlue, darkGreen, darkCyan, darkRed, darkMagenta, darkYellow, gray, darkGray, blue, green, cyan, red, magenta, yellow, white;
}

[StructLayout(LayoutKind.Sequential)]
private struct Colorref
{
    public uint ColorDWORD;
}

After that, it was time to modify the part where the buffer and window were resized:

Console.SetWindowSize(width - 2, height);
Console.SetBufferSize(width, height);

IntPtr stdHandle = GetStdHandle(-11);
ConsoleScreenBufferInfoEx bufferInfo = new ConsoleScreenBufferInfoEx();
bufferInfo.cbSize = (uint)Marshal.SizeOf(bufferInfo);
GetConsoleScreenBufferInfoEx(stdHandle, ref bufferInfo);
++bufferInfo.srWindow.Right;
++bufferInfo.srWindow.Bottom;
SetConsoleScreenBufferInfoEx(stdHandle, ref bufferInfo);

And that’s it! No more ugly black space (at least on my computer, haven’t tested it on other Windows versions).

It works.

solved Remove space left after console scrollbars in C#