How to change the size of the console window?

HWND console = GetConsoleWindow(); RECT r; GetWindowRect(console, &r); //stores the console's current dimensions MoveWindow(console, r.left, r.top, 800, 100, TRUE); // 800 width, 100 height 

It works only vertically.

  • Maybe the window is already 800 wide? And what does the function return, true? - Mishakov Maxim
  • No, if I put more, nothing changes. - Alleksh _
  • Well, how would the vertical size change. - Alleksh _
  • The width of the console window probably depends on the font size and line width. Those. just set the width in pixels probably will not work. - Unick
  • Perhaps it. snap.ashampoo.com/JbFcu4uP - Alleksh _

1 answer 1

Well, in Delphi, when you need to change the size of the console with pens, I use a long-written function:

 function SetConsoleSize(newx,newy:integer):integer; var Rect: TSmallRect; MaxSize,Coord: TCoord; begin MaxSize:=GetLargestConsoleWindowSize(GetStdHandle(STD_OUTPUT_HANDLE)); if (newx > MaxSize.X) or ((newx > MaxSize.X)) then begin Result:=-1; // возвращаем -1, если пытаемся задать очень большой размер exit; end; Rect.Left := 1; Rect.Top := 1; Rect.Right := newx+1; Rect.Bottom := newy+1; Coord.X := Rect.Right + 1 - Rect.Left; // размеры окна должны быть хотя бы на 1 меньше буфера Coord.y := Rect.Bottom + 1 - Rect.Top; SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), Coord); // выставляем размер буфера Result:=integer(SetConsoleWindowInfo(GetStdHandle(STD_OUTPUT_HANDLE), True, Rect)); // выставляем размер окна end; 

I understand that the answer should be in C ++, but there is no C ++ on this machine, I can’t check the correctness of the code, so now I’ll give an explanation so that you can easily translate from Delphi to C ++.

First, we need to determine the maximum possible window size. We do this with the COORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput); function COORD WINAPI GetLargestConsoleWindowSize(HANDLE hConsoleOutput); , passing as a parameter the handle of our window, getting in COORD max values ​​of X and Y. Structure COORD:

 typedef struct _COORD { SHORT X; SHORT Y; } COORD, *PCOORD; 

If everything is in order, you need to set the coordinates, for this is used the structure SMALL_RECT

 typedef struct _SMALL_RECT { SHORT Left; SHORT Top; SHORT Right; SHORT Bottom; } SMALL_RECT; 

and the new buffer size (again through COORD). It must be remembered that the new sizes were applied successfully; the buffer size must be at least 1 larger than the window size. Further simple: use the BOOL WINAPI SetConsoleScreenBufferSize(_In_ HANDLE hConsoleOutput, COORD dwSize); to set the new buffer size and BOOL WINAPI SetConsoleWindowInfo(HANDLE hConsoleOutput, BOOL bAbsolute, const SMALL_RECT *lpConsoleWindow); to set the new size. Return the result if needed.