Windows 新建缓冲区应对高速闪屏问题

高速使用 system("cls") 会导致非常严重的闪屏

新建第二个缓冲区即可解决该问题,操作分为两步,打开缓冲区开关,以及将缓冲区内容输出到控制台

一份无优化的用来比对效果的代码

#include<bits/stdc++.h>
using namespace std;
int main(){
    while(1){
        for(int i='a';i<='z';++i){
            putchar(i);
        }
        system("cls");
    }
}

双缓冲代码

#include<bits/stdc++.h>
#include<windows.h>
HANDLE hOutput;
COORD coord={0,0};
HANDLE hOutBuf=CreateConsoleScreenBuffer(
    GENERIC_READ | GENERIC_WRITE, 
    FILE_SHARE_READ | FILE_SHARE_WRITE, 
    NULL, 
    CONSOLE_TEXTMODE_BUFFER, 
    NULL
);
CONSOLE_CURSOR_INFO cci;
char data[80000];
DWORD bytes=0;
void start_cls(HANDLE hConsole=hOutput){
    COORD coordScreen={0,0}; 
    DWORD cCharsWritten;
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    DWORD dwConSize;
    if (!GetConsoleScreenBufferInfo(hConsole, &csbi)) return;
    dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
    if (!FillConsoleOutputCharacter(hConsole, (TCHAR)' ', dwConSize, coordScreen, &cCharsWritten)) return;
    SetConsoleCursorPosition(hConsole, coordScreen);
}
void Flush_Screen(unsigned Flush_size){
    ReadConsoleOutputCharacterA(hOutput,data,Flush_size,coord,&bytes);
    WriteConsoleOutputCharacterA(hOutBuf,data,Flush_size,coord,&bytes);
}
void set_Flush(){
    hOutput=GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleActiveScreenBuffer(hOutBuf);
    cci.bVisible=0;
    cci.dwSize=1;
    SetConsoleCursorInfo(hOutput,&cci);
    SetConsoleCursorInfo(hOutBuf,&cci);
}
void show(int Flush_size){
    Flush_Screen(Flush_size);
}
int main(){
    set_Flush(); //初始化缓冲信息
    while(1){
        start_cls(); //打开缓冲开关
        for(int c='a';c<='z';c++){
            putchar(c);
        }
        show(100);  //输出到控制台(这里一定要开够,大了可以,但是小了不行)
    }
}
posted @ 2024-10-07 16:03  HaneDaniko  阅读(23)  评论(1编辑  收藏  举报