2022-02-18

console app : prevent key inputs to act on the command line it was started from

I am making a simple windows console application, to try and make an old school game I guess.

I have a function to get key presses , like that :

char GetKeyPressed()
{
    BYTE keys[256] = {0};

    for (size_t i = 0; i < 256; i++)
    {
        keys[i] = GetAsyncKeyState(i);
    }
    for (size_t i = 0; i < 256; i++)
    {
        if (keys[i] != 0)
        {
            // printf("key value : 0x%02x\n", (int)i);
            return i;
        }
    }

    return 0;
}

I works fine.

The issue is : if I start the game in an existing terminal, every key pressed during the game, was also an input in in the original terminal 'current line', even if it's not visible to me ( because the game redraws the content of the console).

When exiting the game, I can see the original content of the terminal prompt + all my inputs during the game run.

Is there a way to 'take ownership' of the inputs ? or prevent them in anyway to end up inside the command line ?

.... some time later ...

I boiled it down to this example :

#include <windows.h>
#include <iostream>

static bool QUIT = false;
void GetKeyPressed()
{
    char keys[256] = {0};

    for (int i = 0; i < 256; i++)
    {
        keys[i] = GetAsyncKeyState(i); // & 0x01;

        if (keys[i])
        {
            if (i == 0x51) // 'q'
            {
                std::cout << "QUITTING !!!!" << std::endl;
                QUIT = true;
                return;
            }
        }
    }
}

int main()
{
    std::cout << "Program Started" << std::endl;
    while (!QUIT)
    {
        GetKeyPressed();
    }    
    return 0;
}

The problem still persist. Pressing 'q' to quit the program leaves the letter q in the command line ... I don't get it.

compiled with : g++ -o example example.cpp


from Recent Questions - Stack Overflow https://ift.tt/R8rYWTs
https://ift.tt/O5oIAD6

No comments:

Post a Comment