I am maiking a CLR Console Application to controll a robot. I am using cki.Key == ConsoleKey::UpArrow
to check if button is pressed and then send message to the robot. I want to stop the robot when no keys are pressed. How can I find out if no keys are pressed?
I was trying Console::KeyAvailable == false
, but then I need to press another button to stop the robot.
What I've tried is below:
With Console::KeyAvailable
:
ConsoleKeyInfo cki;
do{
cki = Console::ReadKey(true);
if (cki.Key == ConsoleKey::UpArrow)
{ /* send message forward*/ }
else if (Console::KeyAvailable == false)
{ /* send message STOP*/ }
}while (cki.Key != ConsoleKey::Escape);
UPDATE code with _kbhit()
(still not working):
ConsoleKeyInfo cki;
do{
cki = Console::ReadKey(true);
if (cki.Key == ConsoleKey::UpArrow)
{ /* send message forward*/ }
else if (_kbhit() == false)
{ /* send message STOP */ }
while (_kbhit())
getch();
}while (cki.Key != ConsoleKey::Escape);
New Idea:
while (true)
{
if (Console::KeyAvailable==1)
{
cki = Console::ReadKey(true);
if (cki.Key == ConsoleKey::UpArrow)
{
Console::WriteLine("Forward");
}
if (cki.Key == ConsoleKey::Escape)
{
Console::WriteLine("Escape");
break:
}
}
else
{
Console::WriteLine("STOP");
}
}
答案 0 :(得分:0)
我建议使用像_kbhit这样的事件监听器功能,它可以检查按键何时以及何时正在释放它,并且可以用作您想要发送的信号类型的条件。您需要包括:conio.h 这应该更好:
do{
int key;
if (_kbhit())
key = getch();
else
key = 0;
if (key==72)
{
// send message forward
}
else if (key=0)
{
// send message STOP
}
}while (cki.Key != ConsoleKey::Escape);
此代码应该更好用
答案 1 :(得分:0)
你可以在c ++中使用_kbhit()函数。如果按任何键,则_kbhit等于1。您必须清除_kbhit缓冲区,否则它将保留1.清除方法是character = getch();这将保存最后输入的字符,您可以比较该字符,并决定对哪个键执行哪个操作。
答案 2 :(得分:0)
如果您将循环更改为while (true)
并使用Console::KeyAvailable
检查密钥是否可用,如果密钥不可用,则发送消息停止,如果可用,则读取密钥并检查它是哪个密钥,如果是UpArrow
,则向前发送消息。如果是Escape
,请打破循环。
ConsoleKeyInfo cki;
while (true){
if (Console::KeyAvailable){
cki = Console::ReadKey(true);
if (cki.Key == ConsoleKey::UpArrow){
// Forward
}
else if (cki.Key == ConsoleKey::Escape){
break;
}
}
else{
// Stop
}
}
也许在那里添加某种睡眠或其他东西,所以你的程序并不总是在处理按下的键时发送停止并且还没有在键盘缓冲区中。