“特定”双缓冲与此代码?

时间:2019-06-26 16:33:11

标签: c++ winapi

对于此代码,我正在尝试实现双缓冲,以便在Windows 10的控制台窗口中更新std::cout时不闪烁。将其实现到当前代码中的最佳方法是什么?我正在查看some Microsoft documentation,但我想不出一种可以将其合并的方法吗?

void ClearScreen()
{
    HANDLE                     hStdOut;
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    DWORD                      count;
    DWORD                      cellCount;
    COORD                      homeCoords = { 0, 0 };

    homeCoords.X = 0;
    homeCoords.Y = 0;

    hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
    if (hStdOut == INVALID_HANDLE_VALUE) return;

    /* Get the number of cells in the current buffer */
    if (!GetConsoleScreenBufferInfo(hStdOut, &csbi)) return;
    cellCount = csbi.dwSize.X * csbi.dwSize.Y;

    /* Fill the entire buffer with spaces */
    if (!FillConsoleOutputCharacter(
        hStdOut,
        (TCHAR) ' ',
        cellCount,
        homeCoords,
        &count
    )) return;

    /* Fill the entire buffer with the current colors and attributes */
    if (!FillConsoleOutputAttribute(
        hStdOut,
        csbi.wAttributes,
        cellCount,
        homeCoords,
        &count
    )) return;

    /* Move the cursor home */
    SetConsoleCursorPosition(hStdOut, homeCoords);
}

1 个答案:

答案 0 :(得分:3)

基本思想是调用CreateConsoleScreenBuffer创建一个屏幕外缓冲区。然后在调用FillConsoleOutputCharacterFillConsoleOutputAttribute等时,通过将句柄传递到该屏幕缓冲区来根据需要清除/填充它。当用户可以查看时,调用SetConsoleActiveScreenBuffer使其成为控制台的活动缓冲区。

请注意,在大多数情况下,您不想在每次清除屏幕时都创建一个新的屏幕缓冲区,而是在启动程序时可能要创建两个屏幕缓冲区,并在两个之间交替显示您编写并显示输出。