您的位置:首页 > 其它

跨平台的检测键盘是否有键按下并返回按键的值

2013-11-24 09:27 295 查看
/**
* @return 0:没有按键按下
*		  其他:有键按下,返回键的值
*/
int GetCharIfKbhit(void);

#ifdef _WINDOWS_
#include <conio.h>

int GetCharIfKbhit(void)
{
int res = _kbhit();
if(res)
res = _getch();
return res;
}

#else
#include <termios.h>
#include <fcntl.h>

int GetCharIfKbhit(void)
{
struct termios oldt, newt;
int ch;
int oldf;

tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);

ch = getchar();

tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
fcntl(STDIN_FILENO, F_SETFL, oldf);

return ch;
}
#endif
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: