Goliat Goliat - 1 month ago 14
C++ Question

check if no key is pressed

I am maiking a CLR Console Application to controll a robot. I am using

cki.Key == ConsoleKey::UpArrow
to check if button is pressed and then send message to the robot. I want to stop the robot when no keys are pressed. How can I find out if no keys are pressed?

I was trying
Console::KeyAvailable == false
, but then I need to press another button to stop the robot.

BEFORE

ConsoleKeyInfo cki;
do{
cki = Console::ReadKey(true);
if (cki.Key == ConsoleKey::UpArrow)
{ // send message forward}
else if (Console::KeyAvailable == false)
{ // send message STOP }

}while (cki.Key != ConsoleKey::Escape);


UPDATE code with
_kbhit()
(still not working):

ConsoleKeyInfo cki;
do{
cki = Console::ReadKey(true);
if (cki.Key == ConsoleKey::UpArrow)
{ // send message forward}
else if (_kbhit() == false)
{ // send message STOP }

while (_kbhit())
getch();

}while (cki.Key != ConsoleKey::Escape);


New Idea:

while (true)
{
if (Console::KeyAvailable==1)
{
cki = Console::ReadKey(true);
if (cki.Key == ConsoleKey::UpArrow)
{
Console::WriteLine("Forward");
}

if (cki.Key == ConsoleKey::Escape)
{
Console::WriteLine("Escape");
break:
}
}
else
{
Console::WriteLine("STOP");
}
}

Answer

What if you change the loop to while (true) and inside loop check if the key is available using Console::KeyAvailable, if the key is not available, send message stop, if it is available, read the key and check which key it is, if it is UpArrow, send message forward. If it is Escape, break the loop.

ConsoleKeyInfo cki;
while (true){

    if (Console::KeyAvailable){
        cki = Console::ReadKey(true);
        if (cki.Key == ConsoleKey::UpArrow){
            // Forward
        }
        else if (cki.Key == ConsoleKey::Escape){
            break;
        }
    }
    else{
        // Stop
    }   
}

And maybe add some kind of sleep or something there, so your program doesn't always send stop whenever the pressed key is being processed and isn't in the keyboard buffer yet.