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

2

I'm creating a text game, where it will have a start 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 be updated, because I have the "setinha" that changes according to the option that the player will select, however, the only way I got it was using system("cls") e writing it all over again. Is there a way I can update what's in cout , without having to delete everything first? For deleting, the text will flash on the screen.

    
asked by anonymous 14.04.2016 / 19:38

1 answer

5

The solution is to create a function that handles the console to clean using the Windows API. This is documented in .

#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);
}
    
14.04.2016 / 19:57