Leo King Leo King - 1 year ago 138
Vb.net Question

How to prevent the Console window being resized in VB.NET?

I need to prevent the user of my console program from resizing the window, only allowing it to be changed programmatically. If the user changes the width, everything messes up. Also, I want to disable the maximise button. Are either of these possible in Console?

This answer neatly covers how to disable resizing a form in WinForms, but it won't work for Console.

Answer Source

I came up with a solution that prevents re-sizing of a console window application (either by dragging the corner border or by clicking on the maximize or minimize buttons). The following code is written in the form of a complete VB.Net console application (i.e., a Module):

Module Module1

    Private Const MF_BYCOMMAND As Integer = &H0
    Public Const SC_CLOSE As Integer = &HF060
    Public Const SC_MINIMIZE As Integer = &HF020
    Public Const SC_MAXIMIZE As Integer = &HF030
    Public Const SC_SIZE As Integer = &HF000

    Friend Declare Function DeleteMenu Lib "user32.dll" (ByVal hMenu As IntPtr, ByVal nPosition As Integer, ByVal wFlags As Integer) As Integer
    Friend Declare Function GetSystemMenu Lib "user32.dll" (hWnd As IntPtr, bRevert As Boolean) As IntPtr

    Sub Main()

        Dim handle As IntPtr
        handle = Process.GetCurrentProcess.MainWindowHandle ' Get the handle to the console window

        Dim sysMenu As IntPtr
        sysMenu = GetSystemMenu(handle, False) ' Get the handle to the system menu of the console window

        If handle <> IntPtr.Zero Then
            DeleteMenu(sysMenu, SC_CLOSE, MF_BYCOMMAND) ' To prevent user from closing console window
            DeleteMenu(sysMenu, SC_MINIMIZE, MF_BYCOMMAND) 'To prevent user from minimizing console window
            DeleteMenu(sysMenu, SC_MAXIMIZE, MF_BYCOMMAND) 'To prevent user from maximizing console window
            DeleteMenu(sysMenu, SC_SIZE, MF_BYCOMMAND) 'To prevent the use from re-sizing console window
        End If

        Do Until (Console.ReadKey.Key = ConsoleKey.Escape)
            'This loop keeps the console window open until you press escape      

    End Sub

End Module

I based this answer off of the Stack Overflow question/answer: "Disable the maximize and minimize buttons of a c# console [closed]"

Please let me know if this doesn't work for you. Good luck!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download