Update console without using system("cls") on Windows

Asked

Viewed 508 times

2

I am creating a text game, where will have an initial menu, follow the code I already have:

#include <iostream>
#include <Windows.h>

using namespace std;

void setTamanhoConsole(int x, int y){
    HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
    SMALL_RECT sr;
    COORD consoleSize;

    consoleSize.X = x;
    consoleSize.Y = y;

    sr.Top = sr.Left = 0;
    sr.Right = x-1; sr.Bottom = y-1;

    SetConsoleScreenBufferSize(console, consoleSize);
    SetConsoleWindowInfo(console, TRUE, &sr);
}

void setPosicaoCursor(int x, int y){
        COORD pos = { x, y };
        HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE);
        SetConsoleCursorPosition(output, pos);
}

bool teclaPressionada(int tecla){
    return GetAsyncKeyState(tecla) & 0x8000;
}

int main(){
    setTamanhoConsole(150, 80); 
    setPosicaoCursor(10, 5);
    int opcao = 1;

    while (true){
        cout << "DUNGEONS!!!" << "\r";
        cout << endl << endl << endl;

        cout << "Novo Jogo ";
        if (opcao == 1) cout << " <-";
        cout << endl;

        cout << "Creditos ";
        if (opcao == 2) cout << " <-";
        cout << endl;

        cout << "Sair ";
        if (opcao == 3) cout << " <-";
        cout << endl;

        if (teclaPressionada(VK_UP))
            opcao--;
        if (teclaPressionada(VK_DOWN))
            opcao++;

        if (opcao > 3) opcao = 1;
        if (opcao < 1) opcao = 3;

        cout << opcao << endl;

        Sleep(100);
        system("cls");
    }



    cin.get();
    return EXIT_SUCCESS;
}

I want this menu to keep updating, because I have the "arrow" that changes according to the option that the player will select, however, the only way I could was using the system("cls") and writing everything again. There is a way for me to update what is on cout, without having to erase everything before? Because deleting, the text is flashing on the screen.

1 answer

6


The solution is to create a function that manipulates the console to clean up using the Windows API. This is demonstrated in the documentation.

#include <windows.h>

void cls() {
   HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
   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
       || !GetConsoleScreenBufferInfo( hConsole, &csbi)
       || !FillConsoleOutputAttribute(hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten))) {
      return;
   }
   SetConsoleCursorPosition(hConsole, coordScreen);
}

I put in the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.