How to make a program do something by pressing a key on the keyboard

Let's say I made a program which would display "Hi" when I hit the 'a' key.

what line of code should I use to do that? and please explain the concept, thanks :)
You could use GetAsyncKeyState, from <windows.h>, to detect the key as long as it is pressed: It will spam Hi as long as you hold the 'a' key.

Otherwise (also simpler) use getch() in a loop and check the value.
1
2
3
4
5
6
7
while(1)
{
    if(getch() == 'a')
    {
        cout<<"Hi!"<<endl;
    }
}


Explanation: Getch() return a key pressed unde char format, and pauses the program when it is called untill a key is pressed.
By checking if the value returned is a specific char (getch()=='a'), you can test for a simple keypress.
Topic archived. No new replies allowed.