Get key press in windows console

前端 未结 2 491
有刺的猬
有刺的猬 2020-12-06 14:31

I found this piece of code online:

CHAR getch() {
    DWORD mode, cc;
    HANDLE h = GetStdHandle( STD_INPUT_HANDLE );

    if (h == NULL) {
        return 0         


        
相关标签:
2条回答
  • 2020-12-06 15:06

    you have a lot of ways to get the keyboard inputs

    you can use GetAsyncKeyState https://msdn.microsoft.com/fr-fr/library/windows/desktop/ms646293(v=vs.85).aspx or GetKeyState https://msdn.microsoft.com/fr-fr/library/windows/desktop/ms646301.aspx

    which are far better than getch

    0 讨论(0)
  • 2020-12-06 15:19

    If stuff like control and alt keys, these are virtual key strokes, they are supplements to characters. You will need to use ReadConsoleInput. But you will get it all, the mouse also. So you really need to filter and return a structure from the call so you know if it is the likes of ctrl-A Alt-A. Filter repeats if you don't want them.

    This may need work, don't know what you are after...

    bool getconchar( KEY_EVENT_RECORD& krec )
    {
        DWORD cc;
        INPUT_RECORD irec;
        HANDLE h = GetStdHandle( STD_INPUT_HANDLE );
    
        if (h == NULL)
        {
            return false; // console not found
        }
    
        for( ; ; )
        {
            ReadConsoleInput( h, &irec, 1, &cc );
            if( irec.EventType == KEY_EVENT
                &&  ((KEY_EVENT_RECORD&)irec.Event).bKeyDown
                )//&& ! ((KEY_EVENT_RECORD&)irec.Event).wRepeatCount )
            {
                krec= (KEY_EVENT_RECORD&)irec.Event;
                return true;
            }
        }
        return false; //future ????
    }
    
    int main( )
    {
        KEY_EVENT_RECORD key;
        for( ; ; )
        {
            getconchar( key );
            std::cout << "key: " << key.uChar.AsciiChar
                << " code:  " << key.wVirtualKeyCode << std::endl;
        }
    }
    

    ReadConsoleInput function

    INPUT_RECORD structure

    KEY_EVENT_RECORD structure

    Virtual-Key Codes

    0 讨论(0)
提交回复
热议问题