Search code examples
c++while-loopexitmultiplatformonkeypress

C++: execute a while loop until a key is pressed e.g. Esc?


Does anyone have a snippet of code that doesn't use windows.h to check for a key press within a while loop. Basically this code but without having to use windows.h to do it. I want to use it on Linux and Windows.

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

int main()
{
    bool exit = false;

    while(exit == false)
    {
        if (GetAsyncKeyState(VK_ESCAPE))
        {
            exit = true;
        }
        std::cout<<"press esc to exit! "<<std::endl;
    }

    std::cout<<"exited: "<<std::endl;

    return 0;
}

Solution

  • Your best bet is to create a custom "GetAsyncKeyState" function that will use #IFDEF for windows and linux to choose the appropriate GetAsyncKeyState() or equivalent.

    No other way exists to achieve the desired result, the cin approach has its problems - such as the application must be in focus.