2

So, I am using GetAsyncKeyState() to see when some key is pressed. But, after using it I need to use getch(). But it seems that getch() gets whatever GetAsyncKeyState() got before again. That is the version of my simplified code:

#include <graphics.h>

int main()
{
    initwindow(100, 100);

    while(true)
    {        
        if (GetAsyncKeyState(VK_RETURN))    //wait for user to press "Enter"
            break;
        //do other stuff
    }

    getch();    //this is just skipped

    return 0;
}

I think I need to clean the input buffer before using getch(). But how? PS: GetAsyncKeyState() is a must-use for me and I have not found any substitute for getch(), which could work with BGI window and which would fix the problem. Hoping for some advice and thank you.

genpfault
  • 51,148
  • 11
  • 85
  • 139
user3496846
  • 1,627
  • 3
  • 16
  • 28

2 Answers2

3

Use FlushConsoleInputBuffer

FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
  • I do not know what I am doing wrong, but it still skips getch. Can the fact that I am working with bgi graphics window be the case? Thanks for your answer. – user3496846 Apr 17 '14 at 10:11
  • @user3496846: Could be. I'm not familiar with bgi graphics. I assumed `getch` was the same as the one from the WINAPI, in which case, this should work. Apparently it's not. What behavior are you trying to get from `getch`? You may be able to simulate it entirely with WINAPI functions. For example, see this answer of mine from another question: http://stackoverflow.com/a/8177635/440119 – Benjamin Lindley Apr 17 '14 at 10:20
  • What I want to do is to read a char from the keyboard without the need for the console window to be active (in my case the BGI window is active). And I do not want the char to be the code of the "Enter" key, which is happening right now. Is there a way to read a char with a WINAPI function? Thank you for you help. – user3496846 Apr 17 '14 at 10:37
0

It is skipping getch() call beacuse of enter pressed by user for the previous input, and getch is getting that char, the function fflush(stdin) we flush the input stream. so that getch() will read the fresh input from input stream.

#include <graphics.h>

int main()
{
    initwindow(100, 100);

    while(true)
    {        
        if (GetAsyncKeyState(VK_RETURN))    //wait for user to press "Enter"
            break;
        //do other stuff
    }
    fflush(stdin);
    getch();    //this is just skipped

    return 0;
}
rajenpandit
  • 1,265
  • 1
  • 15
  • 21
  • Sorry, but it does not seem to work. Even when I put Sleep(1000) right before fflush, the application still skips getch. – user3496846 Apr 17 '14 at 10:07