控制台图像在Windows 10中闪烁

时间:2016-01-12 08:44:09

标签: c++ console-application windows-10 doublebuffered

以下代码在Windows XP中按预期工作,但在Windows 10中,图像开始闪烁。如何在Windows 10中使其工作?

#include <windows.h>
#include <ctime>
#include <vector>

#define xMax 180
#define yMax 45
#define Fps 250

class dbconsole
{
private:
    int width, height, FPS, delay;
    HANDLE h0, h1;
    std::vector<CHAR_INFO> chiBuffer;
    bool curBuffer;
    int drawingTimer;

    void preparebuffer(HANDLE &h)
    {
        CONSOLE_CURSOR_INFO cursor = {false, 1};
        SMALL_RECT windowRectangle = {0,0,width-1,height-1};
        h = CreateConsoleScreenBuffer(
                GENERIC_READ | GENERIC_WRITE,
                FILE_SHARE_READ | FILE_SHARE_WRITE,
                NULL,
                CONSOLE_TEXTMODE_BUFFER,
                NULL);
        SetConsoleCursorInfo(h, &cursor);
        SetConsoleScreenBufferSize (h, {width,height});
        SetConsoleWindowInfo(h,true,&windowRectangle);
    }

public:

    dbconsole(int Width, int Height, int fps)
    {
        chiBuffer.reserve(Width*Height);
        width = Width;
        height = Height;
        FPS = fps;
        preparebuffer(h0);
        preparebuffer(h1);
        curBuffer = 0;
        drawingTimer = clock();
        for (int i = 0; i < xMax; i++) for (int j = 0; j < yMax; j++) chiBuffer[i+width*j] = {'t',16};
    }

    void depict()
    {
        SMALL_RECT srctWriteRect;
        srctWriteRect.Top = 0;
        srctWriteRect.Left = 0;
        srctWriteRect.Bottom = height-1;
        srctWriteRect.Right = width-1;
        if ((clock()-drawingTimer)*FPS>CLOCKS_PER_SEC)
        {
            if (curBuffer)
            {
                WriteConsoleOutput(h0, &chiBuffer[0], {width,height}, {0,0}, &srctWriteRect);
                SetConsoleActiveScreenBuffer(h0);
            }
            else
            {
                WriteConsoleOutput(h1, &chiBuffer[0], {width,height}, {0,0}, &srctWriteRect);
                SetConsoleActiveScreenBuffer(h1);
            }
            curBuffer=!curBuffer;
            drawingTimer = clock();
        }
    }

};

int main(void)
{
    dbconsole myConsole = dbconsole(xMax,yMax,Fps);
    while (true) myConsole.depict();
}

我希望程序显示黑色字母&#39; t&#39;在蓝色背景上,但没有闪烁和双缓冲

1 个答案:

答案 0 :(得分:0)

好的,无论如何,在查看问题之后,这是一个答案。

CONSOLE_CURSOR_INFO被定义为第一个DWORD dwSize和第二个BOOL bVisible,但您使用它就好像第一个和第二个成员在另一个方向。因此,SetConsoleCursorInfo失败,返回值为0GetLastError返回87,即ERROR_INVALID_PARAMETERSee error codes

正确地禁用游标应该可以解决问题,尽管我没有可用于测试的Windows 10。