BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Input / Output
.NET 2.0+

Controlling the Console Window Size

When developing console applications it may be necessary to determine the size of the current window, or to change the dimensions for a specific purpose. These tasks are both made possible using the Console class.

Console Class

When you are writing a command-line application that executes in a console window, you might want to determine the size of the window before outputting text. For example, you might decide to show the progress of your program using a custom progress bar and want that bar to use the correct number of characters to fill the width of the window. In other situations you may want to set the height and width of a console window in order that it fits your application's design.

Determining the size of the console window is made possible with two properties of the Console class. They are WindowHeight and WindowWidth. Both are static members that return the appropriate dimension of the window in characters. If you change the values of the properties, the console window changes size accordingly.

To demonstrate, add the following Main method to a new console application and run the program. This code loops until you press the Enter key. During each iteration of the loop the WindowHeight and WindowWidth properties are read and the current window size is displayed. If you press one of the arrow keys, the window is expanded or contracted, depending upon the key used.

public static void Main()
{
    Console.WriteLine("Arrow keys to resize, Enter to quit");
    Console.CursorVisible = false;
    Console.ForegroundColor = ConsoleColor.Red;
    ConsoleKeyInfo keyInfo;

    do
    {
        Console.CursorLeft = 0;
        Console.CursorTop = 1;
        Console.Write("({0}x{1}) ", Console.WindowWidth, Console.WindowHeight);

        keyInfo = Console.ReadKey();

        switch (keyInfo.Key)
        {
            case ConsoleKey.LeftArrow:
                Console.WindowWidth = Math.Max(Console.WindowWidth - 1, 6);
                break;
            case ConsoleKey.RightArrow:
                Console.WindowWidth = Math.Min(Console.WindowWidth + 1, 100);
                break;
            case ConsoleKey.UpArrow:
                Console.WindowHeight = Math.Max(Console.WindowHeight - 1, 2);
                break;
            case ConsoleKey.DownArrow:
                Console.WindowHeight = Math.Min(Console.WindowHeight + 1, 60);
                break;    
        }
    } while (keyInfo.Key != ConsoleKey.Enter);
}
1 April 2014