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

时间:2016-07-03 23:23:36

标签: vb.net visual-studio-2015 resize console-application window-resize

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

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

2 个答案:

答案 0 :(得分:2)

我提出了一种解决方案,可以防止重新调整控制台窗口应用程序的大小(通过拖动角落边框或单击最大化或最小化按钮)。以下代码以完整的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问题/答案:"Disable the maximize and minimize buttons of a c# console [closed]"

如果这不适合你,请告诉我。祝你好运!

答案 1 :(得分:0)

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

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

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