user385261
user385261

Reputation: 4169

C++: trying to create event-driven for console (but stuck with a problem)

I am trying to make a event-driven program out of a console that display clock time since start of the program.

I created a function:

WORD GetKey(HANDLE input)
{
    INPUT_RECORD Event;
    DWORD Read;

    ReadConsoleInput(input,&Event,1,&Read);

        if(Event.EventType == KEY_EVENT)
        {
            if(Event.Event.KeyEvent.bKeyDown) 
            {
                return Event.Event.KeyEvent.wVirtualKeyCode;
            }
        }
    return 0;
}

Then I used it into the main while() loop. However, when I launched the program, it lags (the displaying clock pause for about 3-5 seconds delay). What's more weird to this problem is when I press and hold '1' key, the lag problem just gone.. :

WORD LastAction = GetKey(input) //this chunk of code lies in the main while(!quit)
switch(LastAction) 
            {
                case VK_ESCAPE:
                    quit = true;
                    break;
                case '1':
                case VK_NUMPAD1:
                    break;
                default:
                    break;
            }

Is it because my understanding of ReadConsoleInput() is not sufficient? or my code isn't efficient?

please advise me on this issue

thx

Upvotes: 1

Views: 844

Answers (1)

Erik
Erik

Reputation: 91310

When there are no events to be read, ReadConsoleInput will block waiting for an event. You need to check for available events using GetNumberOfConsoleInputEvents, then either read events if there are any present, or pause a little while, e.g. Sleep(10), if there's none.

Upvotes: 2

Related Questions