如何防止控制台 window 在 VB.NET 中调整大小?

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

我需要阻止我的控制台程序的用户调整 window 的大小,只允许以编程方式更改它。如果用户更改宽度,一切都会变得混乱。另外,我想禁用最大化按钮。这些在控制台中是否可行?

This answer 简洁地介绍了如何在 WinForms 中禁用调整表单大小,但它不适用于 Console。

我想出了一个解决方案,可以防止调整控制台 window 应用程序的大小(通过拖动角边框或单击最大化或最小化按钮)。以下代码以完整的 VB.Net 控制台应用程序(即模块)的形式编写:

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      
        Loop

    End Sub

End Module

我的这个答案基于 Stack Overflow question/answer:

如果这对您不起作用,请告诉我。祝你好运!

我想对已接受的答案发表评论,但我缺乏声誉...

要防止控制台 window 在您将其捕捉到角落时调整大小,您可以使用

Console.SetBufferSize(80, 24) ' or whatever size you're using...