How to check if a key is pressed in C ++

How can I check if a key is pressed in Windows?

+6
source share
4 answers

As already mentioned, there is no cross-platform way to do this, but on Windows you can do it like this:

The code below checks if the "A" key is pressed.

if(GetKeyState('A') & 0x8000/*Check if high-order bit is set (1 << 15)*/)
{
    // Do stuff
}

In case of a shift or similar, you will need to transfer one of them: https://msdn.microsoft.com/de-de/library/windows/desktop/dd375731(v=vs.85).aspx

if(GetKeyState(VK_SHIFT) & 0x8000)
{
    // Shift down
}

The low-order bit indicates whether the key is being switched.

SHORT keyState = GetKeyState(VK_CAPITAL/*(caps lock)*/);
bool isToggled = keyState & 1;
bool isDown = keyState & 0x8000;

Oh and also don't forget

#include <Windows.h>
+11
source

There is no portable function that allows you to check if a key has hit and continue if not. It always depends on the system.

Linux posix :

Morgan Mattews kbhit(), POSIX . termios.

:

Windows Microsoft _kbhit()

+2

, , ,

"select()", ( , Posix) os.

'select()' 3 , (. man select, FD_SET ..). , , ( )


man:

'select()' " , , " " - (, ). , - (, (2) ...)"

select:

a) fd, , fd , - (, , , ), select ... ", " " - , fd, .

( select) fd ( ). , 1 - , . 1 fd (.. ), 1 , . select "" (, , char).

b) , , fd. fd , , "select()" 0. (.. ). - , , .

fyi - fd 0,1,2... , C 0 STDIN, 1 STDOUT.


Easy test setup: I open a terminal (separate from my console) and type the tty command on that terminal to find my identifier. The answer is usually similar to "/ dev / pts / 0" or 3 or 17 ...

Then I get fd for use in 'select ()' using open:

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

It is useful to disable this value.

Here is a snippet to consider (from a person):

  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
+1
source

Are you talking about a function getchar?

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

-3
source

Source: https://habr.com/ru/post/1666554/


All Articles