linux下怎么实现监听键盘按键

linux下怎么实现监听键盘按键,第1张

在Unix/Linux下,并没有提供int kbhit(void)这个函数。在linux下开发控制台程序时,需要自己编写kbhit()实现的程序了。下面是kbhit在Unix/Linux下的一个实现。用到了一种终端 *** 作库termios。下面是头文件kbhit.h:QUOTE:#ifndef KBHITh#define KBHIThvoid init_keyboard(void)void close_keyboard(void)int kbhit(void)int readch(void)#endif下面式源程序kbhit.c:QUOTE:#include "kbhit.h"#include <stdio.h>#include <termios.h>static struct termios initial_settings, new_settingsstatic int peek_character = -1void init_keyboard(){tcgetattr(0,&initial_settings)new_settings = initial_settingsnew_settings.c_lflag &= ~ICANONnew_settings.c_lflag &= ~ECHOnew_settings.c_lflag &= ~ISIGnew_settings.c_cc[VMIN] = 1new_settings.c_cc[VTIME] = 0tcsetattr(0, TCSANOW, &new_settings)}void close_keyboard(){tcsetattr(0, TCSANOW, &initial_settings)}int kbhit(){unsigned char chint nreadif (peek_character != -1) return 1new_settings.c_cc[VMIN]=0tcsetattr(0, TCSANOW, &new_settings)nread = read(0,&ch,1)new_settings.c_cc[VMIN]=1tcsetattr(0, TCSANOW, &new_settings)if(nread == 1) {peek_character = chreturn 1}return 0}int readch(){char chif(peek_character != -1) {ch = peek_characterpeek_character = -1return ch}read(0,&ch,1)return ch}

自己写函数

#include <stdio.h>  

#include <termios.h>  

  

static struct termios initial_settings, new_settings  

static int peek_character = -1  

void init_keyboard(void)  

void close_keyboard(void)  

int kbhit(void)  

int readch(void)   

void init_keyboard()  

{  

    tcgetattr(0,&initial_settings)  

    new_settings = initial_settings  

    new_settings.c_lflag |= ICANON  

    new_settings.c_lflag |= ECHO  

    new_settings.c_lflag |= ISIG  

    new_settings.c_cc[VMIN] = 1  

    new_settings.c_cc[VTIME] = 0  

    tcsetattr(0, TCSANOW, &new_settings)  

}  

  

void close_keyboard()  

{  

    tcsetattr(0, TCSANOW, &initial_settings)  

}  

  

int kbhit()  

{  

    unsigned char ch  

    int nread  

  

    if (peek_character != -1) return 1  

    new_settings.c_cc[VMIN]=0  

    tcsetattr(0, TCSANOW, &new_settings)  

    nread = read(0,&ch,1)  

    new_settings.c_cc[VMIN]=1  

    tcsetattr(0, TCSANOW, &new_settings)  

    if(nread == 1)   

    {  

        peek_character = ch  

        return 1  

    }  

    return 0  

}  

  

int readch()  

{  

    char ch  

  

    if(peek_character != -1)   

    {  

        ch = peek_character  

        peek_character = -1  

        return ch  

    }  

    read(0,&ch,1)  

    return ch  

}  

   

int main()  

{  

    init_keyboard()  

    while(1)  

    {  

        kbhit()  

        printf("\n%d\n", readch())  

    }  

    close_keyboard()  

    return 0  

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/6231009.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-18
下一篇 2023-03-18

发表评论

登录后才能评论

评论列表(0条)

保存