linux下的键盘检测

话说,仅仅是一个键盘检测就好麻烦。我还是懂的太少了。。。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <string.h>

#define key_ESC 27

void init_keyboard();

void close_keyboard();

int kbhit();

int readch(); /* 相关函数声明 */

static struct termios initial_settings, new_settings;

static int peek_character = -1;         /* 用于测试一个按键是否被按下 */

/* 检测键盘按键的函数 */

int kbhit()

{
    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);
}

/* 用来接收按下的按键,并peek_character = -1恢复状态 */

int readch()

{
    char ch;

    if ( peek_character != -1 )
    {
        ch = peek_character;

        peek_character = -1;

        return(ch);
    }

    read( 0, &ch, 1 );

    return(ch);
}

/* 配置终端函数 */

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 main(int argc, char const *argv[])
{
    int ch = 0;

    init_keyboard();

    printf( "You can put ESC to quit!\n" );
    while ( ch != 27 )
    {


        if ( kbhit() )
        {
            ch = readch();

            if ( ch != 27 )

                printf( "You put %c ! Only put ESC can quit! \n", ch );
        }
    }

    close_keyboard();

    return 0;
}

211223_fhrI_1171834.png


参考:

  1. http://blog.163.com/liang_w_yan/blog/static/210657088201332444016981/

转载于:https://my.oschina.net/itfanr/blog/365285

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值