Click here to Skip to main content
15,891,687 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am writing a console app which monitors the user-input from a console. So I want to detect the user's key presses. This is the first time I've done this, and seem to have had to do a lot of reading to come up with this small chunk of code. So I'm wondering if this really is the best way to do this.

In addition, the wKeyCode is always an upper case value, is there any way to detect lowercase?

And my final question. When I have clicked on the console then type, nothing appears in the console window, unless I capture the key pressed and then write it to the console window using printf(), as in my code. Is this the normal functionality, and is the only way for the user to see what they have typed appear in the console to capture the key press and write it to the console?
HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);

DWORD   saveMode;
SetConsoleMode(hStdin, ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT);
//SetConsoleMode(hStdin, ENABLE_PROCESSED_INPUT);

while(1)
{
     if (WaitForSingleObject(hStdin, INFINITE) == WAIT_OBJECT_0)
     {
    check what event type occurred
    INPUT_RECORD r[512];
    DWORD read;
    ReadConsoleInput(hStdin, r, 512, &read);
    if(r->EventType == KEY_EVENT)
    {
        int k = 2;
        int key = r->Event.KeyEvent.wKeyCode;
        printf ("%c", key);
    }
    //printf("Read: %d\n", read);
     }
}
Posted

1 solution

I would use getch(). Any reason not to?
There is another option:

C++
#include <iostream>

int main()
{
  std::cin.get();
}


Hope this helps,
Pablo.
 
Share this answer
 
Comments
Jackie Lloyd 20-Feb-12 9:26am    
Thankyou everso much - I had forgotten about getche() which seems to do the job nicely.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900