Abdul Ghani
Abdul Ghani

Reputation: 83

How to get direct keyboard input in C++?

I'm currently writing a game in C++ in windows. Everything is going great so far, but my menu looks like this:

1.Go North

2.Go South

3.Go East

4.Go North

5.Inventory

6.Exit

Insert choice -

It works fine, but I have been using that sort of thing for a while and would rather one that you can navigate with the up and down arrows. How would I go about doing this?

Regards in advance

Upvotes: 5

Views: 30452

Answers (3)

Matth
Matth

Reputation: 154

You can use GetAsyncKeyState. It lets you get direct keyboard input from arrows, function buttons (F0, F1 and so on) and other buttons.

Here's an example implementation:

// Needed for these functions
#define _WIN32_WINNT 0x0500
#include "windows.h"
#include "winuser.h"
#include "wincon.h"

int getkey() {

    while(true) {
        // This checks if the window is focused
        if(GetForegroundWindow() != GetConsoleWindow())
            continue;

        for (int i = 1; i < 255; ++i) {
            // The bitwise and selects the function behavior (look at doc)
            if(GetAsyncKeyState(i) & 0x07)
                return i;

        }

        Sleep(250);
    }
}

Upvotes: 1

prathmesh.kallurkar
prathmesh.kallurkar

Reputation: 5696

In Windows, you can use the generic kbhit() function. This function returns true/false depending on whether there is a keyboard hit or not. You can then use the getch() function to read what is present on the buffer.

while(!kbhit()); // wait for input
c=getch();       // read input

You can also look at the scan codes. conio.h contains the required signatures.

Upvotes: 3

aib
aib

Reputation: 47041

Have you considered using a console UI library such as ncurses?

Upvotes: 4

Related Questions