How to change the size of the command prompt in a .NET console application
October 27, 2015 1 Comment
Occasionally you might need to change the size of the console window in a .NET console application. There are methods and properties available in the Console object that enable you to perform this operation easily.
The below code demonstrates how you could annoy your users by constantly changing the window size. The SetWindowSize method accepts two integers: the horizontal column size and the vertical row size:
int[] possibleRowAndColumnSizes = new int[] { 10, 20, 30, 40 }; for (int i = 0; i < 10; i++) { Random r = new Random(); int pos = r.Next(0, 4); int size = possibleRowAndColumnSizes[pos]; Console.SetWindowSize(size, size + 10); Thread.Sleep(1000); }
Note, however, that setting the row size to e.g. 100 throws an exception in my case with the following message:
The value must be less than the console’s current maximum window size of 59 in that dimension. Note that this value depends on screen resolution and the console font.
You can extract the current maximum window sizes with the following properties:
int largestWidth = Console.LargestWindowWidth; int largestHeight = Console.LargestWindowHeight;
In my case these values are 170 for the width and 59 for the height.
Note that SetWindowSize only sets the window size and not the buffer size. The buffer size is the area in the command prompt which can be occupied by text. Text that doesn’t fit into the buffer size will be cut off the screen. If the buffer size is larger than the window size in any direction then you’ll see scroll bars appear either in the bottom or on the right hand size of the window.
Setting the buffer area can be done with the SetBufferSize method which also accepts a width and a height parameter:
Console.SetBufferSize(100, 10000);
Again, there are limits here but they are larger than for the window size: the max value of Int16, i.e. 32767 minus one. The following won’t throw an exception:
Console.SetBufferSize(Int16.MaxValue - 1, Int16.MaxValue - 1);
Removing the “- 1” bit from either parameter will throw an exception:
The console buffer size must not be less than the current size and position of the console window, nor greater than or equal to Int16.MaxValue.
View all various C# language feature related posts here.
Pingback: How to change the size of the command prompt in a .NET console application | Dinesh Ram Kali.