简体   繁体   中英

Maximizing console window - C#

I'm working on a console application on C# and I need to open the console maximized. When I just hit the maximize button on the console window, it maximizes only on height and not in width. I tried to use the following code:

   Console.WindowWidth = 150;
   Console.WindowHeight = 61;

Which works almost as I want on my computer but gives error on some other computers. What should I do to maximize the console?

Can't with the CLR. Need to import Win32 API calls and poke your container window. The following might help.

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
}
    [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);
    }

This works for a .NET 6 Console application:

using System.Runtime.InteropServices;

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

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

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

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

ShowWindow(ThisConsole, MAXIMIZE);
Console.SetWindowSize(Console.LargestWindowWidth, Console.LargestWindowHeight)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM