How To Launch Your Console Application With A Maximized Window

Forgetting your old school CGA, EGA and then VGA displays of rich 8-bit color, 80×25 displays, we now can have all that screen in a console application, all in a window. A console window you can resize, minimize or maximize within the realm of the operating system lying underneath. So. Creating a console app in Visual Studio is quite simple – but it runs off the bat with default settings. Ever wondered how you can maximize that window? Very simple but, unfortunately CLI does not provide a way to handle that so you have to dip into Windows internals. By dip, I mean import one of the core Windows functions, is all.
Here’s how to do it (C#):

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

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

		static void Main(string[] args)
		{
			ShowWindow(Process.GetCurrentProcess().MainWindowHandle, 3); // SW_MAXIMIZE = 3
			Console.ReadKey();
		}
	}
}

What we are doing here is basically allowing a .NET app to access a lower level, non-.NET, pretty much C/C++ level, if maybe even lower to assembly language levels (I am not expert on that so I welcome critique). ShowWindow() function determines how the window is to be shown. hWnd is a pointer – if you don’t know what that is, look it up. Or ask me, I’ll help you with understanding what that is. Your cmdShow is just that – a command sent to a function (a method, if you’re not familiar with low-level programming). Luckily for you, .NET does provide a handle via Process.GetCurrentProcess().MainWindowHandle property so you can bridge it – all you have to do now is pass it on to the imported method with the right parameter.

For more info, if you are a starter and want to dig in, here is a link from Microsoft: Learn more about ShowWindow() function.

Comments and questions are welcome!

This entry was posted in .NET, C#, Coding, System and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *