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

/**
* @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

你可能感兴趣的:(跨平台的检测键盘是否有键按下并返回按键的值)