c++ - 使用此代码的“特定”双缓冲?

标签 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);
}

最佳答案

基本思路是调用CreateConsoleScreenBuffer 来创建离屏缓冲区。然后,当您调用 FillConsoleOutputCharacterFillConsoleOutputAttribute 等时,通过将句柄传递给该屏幕缓冲区来根据需要清除/填充它。当它准备好供用户查看时,调用 SetConsoleActiveScreenBuffer 使其成为控制台的事件缓冲区。

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

关于c++ - 使用此代码的“特定”双缓冲?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56777409/

相关文章:

c++ - 将 unsigned int 分配给结构中的数组枚举时出现编译错误

c++ - C++ 不等式中的逻辑。 If Else 语句

delphi - Delphi 嵌套类中的 EnumWindows

c++ - MessageBeep 线程阻塞

c - 只响应第一个 WM_KEYDOWN 通知?

c++ - C++ 标准是否要求无符号整数的最大值为 2^N-1 形式?

c++ - 从嵌套的 QMap 中获取值(value)

c++ - 在 C/C++ 中进行大文本关键字搜索的最快方法

c++ - 使用 C++ 的密码到期日期?

c++ - 读取内核模式注册表访问?