How to get input from c++ without stopping for user to press a key ?
Is there any way to get input from user in c++ such that I get input when he presses any key, if he did not press any key then program should proceed.
When we use getch(), then program waits for user to press something and then it proceeds but I want a method such that program will rum but when user presses a key it should respond to it.
I tried ReadConsoleInput(...); but it does not work, it still waits for Input.
Thanks.
Re: How to get input from c++ without stopping for user to press a key ?
One way is to use PeekConsoleInput(). This is very similar to ReadConsoleInput() except that it doesn't remove the record from the buffer and returns immediately if no input is available (lpNumberOfEventsRead is 0). If input is available (lpNumberOfEventsRead is not 0), then use ReadConsoleInput() to obtain the data.
See https://msdn.microsoft.com/en-us/lib...(v=vs.85).aspx
There is also GetNumberOfConsoleInputEvents() - but this also indicates the number of mouse and window-resizing input records as well as keyboard records. See https://msdn.microsoft.com/en-us/lib...(v=vs.85).aspx
Re: How to get input from c++ without stopping for user to press a key ?
Quote:
When we use getch(), then program waits for user to press something and then it proceeds
...or alternately, if you don't need the functionality of the console functions, then _kbhit() will determine if a key has been pressed or not. See https://msdn.microsoft.com/en-us/library/58w7c94c.aspx. Then if a key has been pressed use getch() to get the character.
Re: How to get input from c++ without stopping for user to press a key ?
Quote:
Originally Posted by
2kaud
Thanks the function worked.
I have one more question.
The function will report true every frame if the a button is just held down, I don't want that,
Is there a way so that the function report true in only one frame if a button is held down and is not released, and subsequent frames the function returns false ?
Like if I press and hold 'a' then the function reports true and if I keep hold it then function returns false in frames after that.
Re: How to get input from c++ without stopping for user to press a key ?
Quote:
Is there a way so that the function report true in only one frame if a button is held down and is not released, and subsequent frames the function returns false ?
I don't think so directly. However, what about a loop that tests _kbhit() and retrieves chars until no more remain? Something like
Code:
int ch = 0;
if (_kbhit()) {
ch = getch();
while (_kbhit())
getch();
}
Re: How to get input from c++ without stopping for user to press a key ?
Quote:
Originally Posted by
2kaud
I don't think so directly. However, what about a loop that tests _kbhit() and retrieves chars until no more remain? Something like
Code:
int ch = 0;
if (_kbhit()) {
ch = getch();
while (_kbhit())
getch();
}
Yes I got this also working. Thank you very very much.