2025年linux检测按键

linux检测按键出处 https stackoverflo com questions detecting keyboard key press and release on linux include stdlib h include stdio h include string h string h stdio h stdlib h

大家好,我是讯享网,很高兴认识大家。

出处:https://stackoverflow.com/questions//detecting-keyboard-key-press-and-release-on-linux


讯享网

#include <stdlib.h> #include <stdio.h> #include <string.h> #include <sysexits.h> #include <glob.h> #include <linux/input.h> #include <sys/stat.h> #include <fcntl.h> /* Return -1 if no key is being pressed, or else the lowest keycode (c.f. linux/input-event-codes.h) of all the keys that are being pressed */ int keycode_of_key_being_pressed() { 
    FILE *kbd; glob_t kbddev; // Glob structure for keyboard devices glob ("/dev/input/by-path/*-kbd", 0, 0, &kbddev); // Glob select all keyboards int keycode = -1; // keycode of key being pressed for (int i = 0; i < kbddev.gl_pathc ; i++) { 
    // Loop through all the keyboard devices ... if (! (kbd = fopen (kbddev.gl_pathv[i], "r"))) { 
    // ... and open them in turn (slow!) perror ("Run as root to read keyboard devices"); exit (1); } char key_map[KEY_MAX / 8 + 1]; // Create a bit array the size of the number of keys memset (key_map, 0, sizeof (key_map)); // Fill keymap[] with zero's ioctl (fileno (kbd), EVIOCGKEY (sizeof (key_map)), key_map); // Read keyboard state into keymap[] for (int k = 0; k < KEY_MAX / 8 + 1 && keycode < 0; k++) { 
    // scan bytes in key_map[] from left to right for (int j = 0; j < 8 ; j++) { 
    // scan each byte from lsb to msb if (key_map[k] & (1 << j)) { 
    // if this bit is set: key was being pressed keycode = 8 * k + j ; // calculate corresponding keycode break; // don't scan for any other keys } } } fclose (kbd); if (keycode) break; // don't scan for any other keyboards } return keycode; } void main() { 
    setvbuf (stdout, NULL, _IONBF, 0); // Set stdout unbuffered while (1) { 
    int key = keycode_of_key_being_pressed(); printf ( (key < 0 ? "no key\n" : "keycode: %d\n"), key); if (key == KEY_X) exit (0); } } 

讯享网
小讯
上一篇 2025-03-14 13:11
下一篇 2025-01-06 08:58

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/22497.html