更改控制台大小时的控制台缓冲区问题(WinAPI)

时间:2016-02-20 22:46:34

标签: winapi

我尝试使用WinApi更改控制台大小,我已成功更改窗口的大小等但是当我打印到控制台时,我没有在控制台窗口中打印所有信息,我不明白为什么这是发生了什么?当我删除调整大小代码一切正常。我认为这个问题与控制台缓冲区的大小相关。 首先在main中调用SetConsoleSize(int,int)。

#include <iostream>
#include <stdexcept>
#include <windows.h>

static void SetConsoleSize(int x, int y) {
 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
 SetConsoleTitle("Title!");

 COORD coordinates;
 coordinates.X = x;
 coordinates.Y = y;

 SMALL_RECT windowRect;
 windowRect.Top = 0;
 windowRect.Left = 0;
 windowRect.Bottom = x - 1;
 windowRect.Right = y - 1;

 // Adjust buffer size:
 HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
 if (!SetConsoleScreenBufferSize(handle, coordinates))
     throw std::runtime_error("Unable to resize screen buffer.");

 // display as a maximized window
 ShowWindow(GetConsoleWindow(), SW_MAXIMIZE);
}

1 个答案:

答案 0 :(得分:0)

窗口中的信息被覆盖,因为控制台窗口的缓冲区很小,请参阅COORD坐标,该坐标决定控制台窗口缓冲区的大小。

下面的解决方案代码,观察不同的屏幕尺寸可能会导致问题,因为eval屏幕尺寸的代码只有起始位置{0,0}作为起始位置:

static void SetConsoleSize() {
 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
 SetConsoleTitle("Title);

 CONSOLE_SCREEN_BUFFER_INFO sbInfo;
 GetConsoleScreenBufferInfo(hStdOut, &sbInfo);

 COORD coordinates;
 coordinates.X = 80; // size of line.
 coordinates.Y = 1000; //Number of lines.

 SMALL_RECT windowRect;
 windowRect.Top = 0;
 windowRect.Left = 0;
 windowRect.Bottom = 40;
 windowRect.Right = 79;

 //set textbuffer size
 assert(SetConsoleScreenBufferSize(hStdOut, coordinates));

 //change window size.
 assert(SetConsoleWindowInfo(hStdOut, true, &windowRect));

 const HWND hwnd = GetConsoleWindow();

 SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE); //Positioning the    window
}