最大化控制台窗口 - C#

use*_*830 17 .net c# console console-application visual-studio

我正在使用C#上的控制台应用程序,我需要打开最大化的控制台.当我按下控制台窗口上的最大化按钮时,它仅在高度上而不是在宽度上最大化.我试着使用以下代码:

   Console.WindowWidth = 150;
   Console.WindowHeight = 61;
Run Code Online (Sandbox Code Playgroud)

它几乎可以在我的计算机上运行,​​但在其他一些计算机上出错.我该怎么做才能最大化控制台?

Joh*_* Wu 26

不能与CLR.需要导入Win32 API调用并戳你的容器窗口.以下可能有所帮助.

using System.Diagnostics;
using System.Runtime.InteropServices;

[DllImport("user32.dll")]
public static extern bool ShowWindow(System.IntPtr hWnd, int cmdShow);

private static void Maximize()
{
    Process p = Process.GetCurrentProcess();
    ShowWindow(p.MainWindowHandle, 3); //SW_MAXIMIZE = 3
}
Run Code Online (Sandbox Code Playgroud)


小智 9

    [DllImport("kernel32.dll", ExactSpelling = true)]

    private static extern IntPtr GetConsoleWindow();
    private static IntPtr ThisConsole = GetConsoleWindow();

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]

    private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
    private const int HIDE = 0;
    private const int MAXIMIZE = 3;
    private const int MINIMIZE = 6;
    private const int RESTORE = 9;


    static void Main(string[] args)
    {
       ShowWindow(ThisConsole, MINIMIZE);
    }
Run Code Online (Sandbox Code Playgroud)

  • 我想它应该是“ShowWindow(ThisConsole, MAXIMIZE);” (3认同)
  • 请提供一些解释,为什么代码可以解决问题.不鼓励仅使用代码答案. (2认同)