Patrik Bak
Patrik Bak

Reputation: 538

C# Console Disable Resize

How to achieve programmatically that the console window is not resizable.

I don't want user to change the console window size with their mouse.

Upvotes: 4

Views: 5080

Answers (2)

Elaskanator
Elaskanator

Reputation: 1216

See the answer in this post on MSDN. It requires p-invoking:

private const int MF_BYCOMMAND = 0x00000000;
public const int SC_CLOSE = 0xF060;
public const int SC_MINIMIZE = 0xF020;
public const int SC_MAXIMIZE = 0xF030;
public const int SC_SIZE = 0xF000;//resize

[DllImport("user32.dll")]
public static extern int DeleteMenu(IntPtr hMenu, int nPosition, int wFlags);

[DllImport("user32.dll")]
private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);

[DllImport("kernel32.dll", ExactSpelling = true)]
private static extern IntPtr GetConsoleWindow();

static void Main(string[] args)
{
    IntPtr handle = GetConsoleWindow();
    IntPtr sysMenu = GetSystemMenu(handle, false);

    if (handle != IntPtr.Zero)
    {
        DeleteMenu(sysMenu, SC_CLOSE, MF_BYCOMMAND);
        DeleteMenu(sysMenu, SC_MINIMIZE, MF_BYCOMMAND);
        DeleteMenu(sysMenu, SC_MAXIMIZE, MF_BYCOMMAND);
        DeleteMenu(sysMenu, SC_SIZE, MF_BYCOMMAND);//resize
    }
    Console.Read();
}

Note that this does not prevent Windows window snapping (e.g. dragging window to edge of screen, Win+Left and Win+Right)

Since you're trying to disable resizing, I'm guessing you won't want scrollbars either. For that, see this answer to Remove space left after console scrollbars in C# (leftover after matching Console.SetWindowSize and SetBufferSize; also requires p-invoking to "fix").

Upvotes: 4

David BS
David BS

Reputation: 1892

I'm not sure you can avoid that kind of action. But you may try to use WindowHeight, WindowWidth, LargestWindowHeight and LargestWindowWidth. See this: https://msdn.microsoft.com/pt-br/library/system.console(v=vs.110).aspx

Upvotes: -3

Related Questions