cwinapiconsoledouble-buffering

Use Writefile function to put string in inactive screen buffer in C


I am a highschool student in Korea and I am interested in making window console game in C. For making game, I want to use technique called Double buffering to make smooth game play screen. For doing that, I make plan. First, make two console screen buffer. Second, Write some string in second screen buffer while I show first screen buffer to user. Third, make second screen buffer active.

However, when I did this, the string that I want to write in the second screen buffer is written in the first screen buffer. This is my code.

#include <stdio.h>
#include <Windows.h>

int main()
{
    HANDLE hBuffer[2];
    COORD  size = { 150, 40 };
    COORD  Coor = { 50, 30 };
    SMALL_ RECT rect;
    DWORD  dw;

    rect.Left = 0;
    rect.Right = 150 - 1;
    rect.Top = 0;
    rect.Bottom = 40 - 1;

    hBuffer[0] = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
    SetConsoleScreenBufferSize(hBuffer[0], size);
    SetConsoleWindowInfo(hBuffer[0], TRUE, &rect);

    hBuffer[1] = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
    SetConsoleScreenBufferSize(hBuffer[1], size);
    SetConsoleWindowInfo(hBuffer[1], TRUE, &rect);

    SetConsoleActiveScreenBuffer(hBuffer[1]);
    Sleep(1000);
    SetConsoleCursorPosition(hBuffer[0], Coor);
    Sleep(1000);
    WriteFile(hBuffer[0], "asd", strlen("asd"), &dw, NULL);
    Sleep(1000);
    SetConsoleActiveScreenBuffer(hBuffer[0]);

    while (1) 
    {
    }
}

I intend to write string "asd" in second screen buffer but the string "asd" is written in first screen buffer. I think this problem comes from my misconception of WriteFile function. when I type WriteFile(hBuffer[1], ...); It doesn't mean that I want to Write string to second screen buffer? and How to write string to second screen buffer while second screen buffer is inactive?


Solution

  • When I was playing with it many ago I was using another functions (not the file ones) WriteConsoleOutput and ReadConsoleOutput

    https://learn.microsoft.com/en-us/windows/console/reading-and-writing-blocks-of-characters-and-attributes