5

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

Abdul Ghani
  • 83
  • 1
  • 2
  • 6
  • Not sure if arrows are handled the same across platforms. So, which platform? Also, what have you tried? – Mr Lister Feb 17 '12 at 10:14
  • Very recent similar question: http://stackoverflow.com/questions/9324806/how-to-read-standard-input-continuously – BoBTFish Feb 17 '12 at 10:16

3 Answers3

4

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

aib
  • 45,516
  • 10
  • 73
  • 79
3

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.

JDong
  • 2,304
  • 3
  • 24
  • 42
prathmesh.kallurkar
  • 5,468
  • 8
  • 39
  • 50
1

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);
    }
}
Matth
  • 154
  • 7