前几天在c#版中看到一个帖子:“如何用c#实现,在while (true)循环中,按Esc键退出循环?" 那时候以为只能用hook来监视键盘,看了看后面一些猩猩的回复,只怪自己c#太菜,都没有看明白:( 昨天在c版看到又有人问这个问题,其中cyberHunK(→迈克·老猫←) 用了_kbhit()来解决了这个问题,我又去查了查MSDN,才有点明白,终于知道了还有_kbhit()这样的函数(汗。。。)。觉得这个东西蛮有用的,就记下来,有错的地方还请各位指教! 先抄一段MSDN对_kbhit()的解释: int _kbhit( void ); Return Value _kbhit returns a nonzero value if a key has been pressed. Otherwise, it returns 0.
Remarks The _kbhit function checks the console for a recent keystroke. If the function returns a nonzero value, a keystroke is waiting in the buffer. The program can then call _getch or _getche to get the keystroke. 所以在vc里面可以用下面这个程序来实现按ESC退出while循环 #include #include //包含对 _kbhit()和_getch()声明
int main() { bool flag = true; char unch; while(flag) if(_kbhit() && (unch = _getch()) == 0x1b ) flag = false; //ESC的键盘扫描码是0x1b return 0; } //vc6.0下编译运行通过 呵呵,原来这么简单!基本的用法就是这样了,你可以在里面加些代码来实现复杂一些的功能。 那类似这样的功能用c#该怎么实现呢?笨点儿的办法就是引用dll,在c#里面调用_kbhit()来实现。(因为_kbhit()是vc这个编译器特有的系统函数)