[c++] How do I check if a Key is pressed on C++

How could I possibly check if a Key is pressed on Windows?

This question is related to c++ keyboard key

The answer is


check if a key is pressed, if yes, then do stuff

Consider 'select()', if this (reportedly Posix) function is available on your os.

'select()' uses 3 sets of bits, which you create using functions provided (see man select, FD_SET, etc). You probably only need create the input bits (for now)


from man page:

'select()' "allow a program to monitor multiple file descriptors, waiting until one or more of the file descriptors become "ready" for some class of I/O operation (e.g., input possible). A file descriptor is considered ready if it is possible to perform a corresponding I/O operation (e.g., read(2) without blocking...)"

When select is invoked:

a) the function looks at each fd identified in the sets, and if that fd state indicates you can do something (perhaps read, perhaps write), select will return and let you go do that ... 'all you got to do' is scan the bits, find the set bit, and take action on the fd associated with that bit.

The 1st set (passed into select) contains active input fd's (typically devices). Probably 1 bit in this set is all you will need. And with only 1 fd (i.e. an input from keyboard), 1 bit, this is all quite simple. With this return from select, you can 'do-stuff' (perhaps, after you have fetched the char).

b) the function also has a timeout, with which you identify how much time to await a change of the fd state. If the fd state does not change, the timeout will cause 'select()' to return with a 0. (i.e. no keyboard input) Your code can do something at this time, too, perhaps an output.

fyi - fd's are typically 0,1,2... Remembe that C uses 0 as STDIN, 1 and STDOUT.


Simple test set up: I open a terminal (separate from my console), and type the tty command in that terminal to find its id. The response is typically something like "/dev/pts/0", or 3, or 17...

Then I get an fd to use in 'select()' by using open:

// flag options are: O_RDONLY, O_WRONLY, or O_RDWR
int inFD = open( "/dev/pts/5", O_RDONLY ); 

It is useful to cout this value.

Here is a snippet to consider (from man select):

  fd_set rfds;
  struct timeval tv;
  int retval;

  /* Watch stdin (fd 0) to see when it has input. */
  FD_ZERO(&rfds);
  FD_SET(0, &rfds);

  /* Wait up to five seconds. */
  tv.tv_sec = 5;
  tv.tv_usec = 0;

  retval = select(1, &rfds, NULL, NULL, &tv);
  /* Don't rely on the value of tv now! */

  if (retval == -1)
      perror("select()");
  else if (retval)
      printf("Data is available now.\n");  // i.e. doStuff()
      /* FD_ISSET(0, &rfds) will be true. */
  else
      printf("No data within five seconds.\n"); // i.e. key not pressed

There is no portable function that allows to check if a key is hit and continue if not. This is always system dependent.

Solution for linux and other posix compliant systems:

Here, for Morgan Mattews's code provide kbhit() functionality in a way compatible with any POSIX compliant system. He uses the trick of desactivating buffering at termios level.

Solution for windows:

For windows, Microsoft offers _kbhit()


Are you talking about getchar function?

http://en.cppreference.com/w/c/io/getchar


Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to keyboard

How do I check if a Key is pressed on C++ Move a view up only when the keyboard covers an input field Move textfield when keyboard appears swift Xcode iOS 8 Keyboard types not supported Xcode 6: Keyboard does not show up in simulator How to dismiss keyboard iOS programmatically when pressing return Detect key input in Python Getting Keyboard Input Press Keyboard keys using a batch file Keylistener in Javascript

Examples related to key

How do I check if a Key is pressed on C++ Map<String, String>, how to print both the "key string" and "value string" together Python: create dictionary using dict() with integer keys? SSH Key: “Permissions 0644 for 'id_rsa.pub' are too open.” on mac SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch How to get the stream key for twitch.tv How to get key names from JSON using jq How to add multiple values to a dictionary key in python? Initializing a dictionary in python with a key value and no corresponding values How can I sort a std::map first by value, then by key?