C non-blocking keyboard input

前端 未结 10 918
说谎
说谎 2020-11-22 05:59

I\'m trying to write a program in C (on Linux) that loops until the user presses a key, but shouldn\'t require a keypress to continue each loop.

Is there a simple wa

10条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 06:35

    Another way to get non-blocking keyboard input is to open the device file and read it!

    You have to know the device file you are looking for, one of /dev/input/event*. You can run cat /proc/bus/input/devices to find the device you want.

    This code works for me (run as an administrator).

      #include 
      #include 
      #include 
      #include 
      #include 
      #include 
    
      int main(int argc, char** argv)
      {
          int fd, bytes;
          struct input_event data;
    
          const char *pDevice = "/dev/input/event2";
    
          // Open Keyboard
          fd = open(pDevice, O_RDONLY | O_NONBLOCK);
          if(fd == -1)
          {
              printf("ERROR Opening %s\n", pDevice);
              return -1;
          }
    
          while(1)
          {
              // Read Keyboard Data
              bytes = read(fd, &data, sizeof(data));
              if(bytes > 0)
              {
                  printf("Keypress value=%x, type=%x, code=%x\n", data.value, data.type, data.code);
              }
              else
              {
                  // Nothing read
                  sleep(1);
              }
          }
    
          return 0;
       }
    

提交回复
热议问题