使用kbhit函数判断键盘有无按键(非阻塞)

平时使用getch()时,如果没有按键,则一直在等待,会打断主循环。

可以使用_kbhit()函数先判断是否有按键,若有,再调用getch()去读取。


例如:

#include <conio.h>
INT16 DBG_GetChar(void)
{
	INT32 n = _kbhit();

	if (n == 0)
	{
		return 0;
	}

	return _getch();
};





msdn中关于_kbhit()的说明:

_kbhit

Checks the console for keyboard input.

int _kbhit( void );

RoutineRequired HeaderCompatibility
_kbhit<conio.h>Win 95, Win NT

For additional compatibility information, see Compatibility in the Introduction.

Libraries

LIBC.LIBSingle thread static library, retail version
LIBCMT.LIBMultithread static library, retail version
MSVCRT.LIBImport library for MSVCRT.DLL, retail version

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.

Example

/* KBHIT.C: This program loops until the user
 * presses a key. If _kbhit returns nonzero, a
 * keystroke is waiting in the buffer. The program
 * can call _getch or _getche to get the keystroke.
 */

#include <conio.h>
#include <stdio.h>

void main( void )
{
   /* Display message until key is pressed. */
   while( !_kbhit() )
      _cputs( "Hit me!! " );

   /* Use _getch to throw key away. */
   printf( "\nKey struck was '%c'\n", _getch() );
   _getch();
}

Output

Hit me!! Hit me!! Hit me!! Hit me!! Hit me!! Hit me!! Hit me!!
Key struck was 'q' 

Console and Port I/O Routines


Send feedback to MSDN. Look here for MSDN Online resources.


Rust语言本身没有提供类似于C语言中的`kbhit()`函数,该函数用于检测键盘是否有按键按下。不过,你可以使用第三方库来实现类似的功能。 一个常用的库是`termion`,它提供了对终端操作的支持。你可以使用`termion`库中的`async_stdin()`函数检测键盘输入。下面是一个使用`termion`库来实现类似于`kbhit()`函数的示例: 首先,在你的Cargo.toml文件中添加`termion`依赖: ```toml [dependencies] termion = "1.5.5" ``` 然后,你可以使用以下代码来检测键盘输入: ```rust use std::io::{self, Read}; use termion::async_stdin; fn main() { // 创建异步输入流 let stdin = async_stdin(); let mut stdin = stdin.lock(); // 设置非阻塞模式 let _ = termion::input::TermRead::set_nonblocking(&mut stdin); loop { // 尝试读取单个字符 let mut buf = [0u8; 1]; if let Ok(_) = stdin.read_exact(&mut buf) { // 检测键盘输入 println!("Key pressed: {}", buf[0]); } // 其他逻辑处理 // ... } } ``` 在上面的示例中,我们使用`async_stdin()`函数创建了一个异步输入流。然后,我们将输入流设置为非阻塞模式,以便在没有输入时不会阻塞程序。接下来,我们使用循环来持续检测键盘输入。当检测按键按下时,我们打印出按下的键码。 请注意,该示例仅演示了如何使用`termion`库来检测键盘输入,并不是完整的实现。你可以根据自己的需求进行扩展和适应。 希望这个示例对你有帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值