I'm writing a c++ console program for Windows using the windows.h include.
I've been trying to tailor the console size to fit my program output, but without finding a reliable way to obtain the value for width and height of a "cell" (the character boxes). I've tried both GetConsoleFontSize and GetConsoleScreenBufferInfo + GetDesktopWindow as demonstrated in the code sample below.
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_FONT_INFO font_size;
GetConsoleFontSize(hOut,GetCurrentConsoleFont(hOut, false, &font_size));
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hOut, &csbi);
RECT desktop;
// Get a handle to the desktop window
const HWND hDesktop = GetDesktopWindow();
// Get the size of screen to the variable desktop
GetWindowRect(hDesktop, &desktop);
// Calculate size of one cell in the console, expressed in pixels.
COORD cell;
// Screen width/max number of columns
cell.X = desktop.right/ csbi.dwMaximumWindowSize.X;
// Screen height/max number of rows
cell.Y = desktop.bottom / csbi.dwMaximumWindowSize.Y;
// Change console size
HWND console = GetConsoleWindow();
MoveWindow(console, 0, 0, 10 * cell.X * 2, 10 * cell.Y, TRUE);
MoveWindow(console, 0, 0, 10 * font_size.dwFontSize.X * 2, 10 * font_size.dwFontSize.Y, TRUE);
Of both attempts I expected a square window able to contain just about 20x10 cells (the height of the cells seem to be 2x the width), with some margin of error on one of the examples given the integer division. However, they both seemed to be approximately 25% too small, apart from the width of the first example with is about 10% too large.
I assume that the font size does not include the spacing between letters and that the dependencies of .dwMaxWindowSize (such as buffer size etc) comes into play, but I can't quite get either method straight.
If anyone has any knowledge of how to obtain the width/height of the cells in pixels reliably I'd be very grateful. Any information regarding what goes into the cells, what affects the return value of either function or other functions I can use to achieve my goal.
Also note that the size is ultimately going to be bigger, but since I wanted to manually count the rows/columns to debug I made it smaller.
GetClientRectto only count the client area of the window instead of the total size of the window. docs.microsoft.com/en-us/windows/win32/api/winuser/…. Also you probably don't need the font size if you just donewClientWidth = oldClientWidth * newBufferColumns / oldBufferColumnsand same with height/rows. And to set the window size you'd probably need to convert between client size and window size, but I imagine that to be a constant difference:newWindowWidth = newClientWidth + oldWindowWidth - oldClientWidthor something like that.