I tried Maximizing the Console .NET application using C# commands, but it doesn’t work.
EDIT: I feel the need to specify that I use “Console App (.NET Framework)” and not “(Console App (NET Core))”
.NET Version is: 4.7.2
Windows version is: Windows 11 (With the new Terminal as my CMD)
This is what I tried:
Example1:
using System;
using System.Runtime.InteropServices;
[DllImport("kernel32.dll", ExactSpelling = true)]
private static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private const int MAXIMIZE = 3;
private const int MINIMIZE = 6;
static void Main(string[] args)
{
ShowWindow(GetConsoleWindow(), MAXIMIZE);
Console.ReadKey();
}
With this first example, if you type “MINIMIZE” instead of “MAXIMIZE”, It does minimize, but it doesn’t MAXIMIZE…
Example2:
[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
}
static void Main(string[] args)
{
Maximize();
Console.ReadKey();
}
Your code runs fine in Windows 10, but if you select Windows Terminal in Win11, your code will not work.
If you are using Win11:
Please open Settings=>Privacy&security=>For developers=>Terminal=>Change to Windows Console Host
At this point, you can maximize the console program by using the code you provided again.
using System;
using System.Runtime.InteropServices;
[DllImport("kernel32.dll", ExactSpelling = true)]
private static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private const int MAXIMIZE = 3;
private const int MINIMIZE = 6;
static void Main(string[] args)
{
ShowWindow(GetConsoleWindow(), MAXIMIZE);
Console.ReadKey();
}
Does this answer your question? Maximizing console window – C#
micorsoft recommends stackoverflow.com/a/72326974/5193536
@Mikael I tried all 3 of them, in fact 2 of the examples I listed are literally from that page. But it is from 2014 so I thought things might have changed since then. A few months back I tried to do the same with a Forms application and it didin’t work. Now I need it for a Console app.
@nbk As for the 2nd comment, for some reason it doesn’t work either. I even tried starting the program from the build just in case, (And not debug)
Which .net version are you using and which windows version? I just tried your first example in .net core 6 and it maximized perfectly.
Show 4 more comments