• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
MKT-porter
博客园    首页    新随笔    联系   管理    订阅  订阅
c/c++非阻塞键盘输入监听 Windows/Linux
  • https://blog.csdn.net/a8821418/article/details/106492074
  • Windows下c代码
#include <conio.h>
#include <windows.h>
#include <iostream>
using namespace std;
int main()
{
	while (!_kbhit())
	{ 
		cout << "Hit me!!" << endl;
		Sleep(50);
	}
	printf("\nKey struck was '%c'\n", _getch());
	//_getch();
	system("pause");
}

  

  • Linux下
#include <stdio.h>
#include <stdlib.h>
 
#define TTY_PATH            "/dev/tty"
#define STTY_US             "stty raw -echo -F "
#define STTY_DEF            "stty -raw echo -F "
 
int get_char();
 
int get_char()
{
    fd_set rfds;
    struct timeval tv;
    int ch = 0;
 
    FD_ZERO(&rfds);
    FD_SET(0, &rfds);
    tv.tv_sec = 0;
    tv.tv_usec = 10; //设置等待超时时间
 
    //检测键盘是否有输入
    if (select(1, &rfds, NULL, NULL, &tv) > 0){
        ch = getchar(); 
    }
    return ch;
}
 
int main(){
    int ch = 0;
    system(STTY_US TTY_PATH);
    // esc=27  
    while(1){
        ch = get_char();
        if(ch != 0){
            printf("%d\n\r",ch);
        }
        if(ch == 3){
            system(STTY_DEF TTY_PATH);
            return 0;
        }         
    }
}

  

posted on 2022-12-26 19:23  MKT-porter  阅读(685)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3