C ++当用户按箭头键时检测 [英] C++ Detect when user presses arrow key
问题描述
我在C ++控制台应用程序中检测到箭头按键时遇到问题。我已经尝试了一切,我发现,在这里和其他教程网站,但所有的人给我相同的东西,当我按下箭头:
I have been having a problem with detecting arrow key presses in my C++ console application. I have tried everything I have found, both here and on other tutorial sites, but all of them give me the same thing whenever I press the arrow:
Process returned 0 <0x0> execution time : 2.249 s
Press any key to continue.
这里是检测我尝试的按键的所有方法, 。这些是我的代码中只剩下两个,其他我试图我删除,而不是注释掉。
Here are all the methods of detecting the key press that I have tried, all ending up the same way. These are the only two left in my code, the others I attempted I deleted instead of commenting out.
方法一:
c1 = getch();
if(c1 == 0)
{
c2 = getch();
if(c2 == 72) {cout << endl << "Up Arrow" << endl;}
else if(c2 == 80) {cout << endl << "Down Arrow" << endl;}
else{cout << endl << "Incorrect Input" << endl;}
}
方法二:
switch(getch()) {
case 65:
cout << endl << "Up" << endl;//key up
break;
case 66:
cout << endl << "Down" << endl; // key down
break;
case 67:
cout << endl << "Right" << endl; // key right
break;
case 68:
cout << endl << "Left" << endl; // key left
break;
}
我的代码中有一些错误,让我回到我的主要方法,还是跳过了一些代码?有更快的方法吗?我几乎100%确定我的其他代码与这个问题没有任何关系,因为我孤立的代码从依赖于程序的任何其他方面,我一直有同样的问题。
Is there some error in my code which made me go back to my main method, or did it skip over some code? Is there a faster way to do this? I'm almost 100% sure that my other code doesn't have anything to do with this problem, because I isolated the code from be dependent on any other aspect of the program, and I kept having the same problem.
再次,我尝试了每一种获得箭头按键的方法,我可以找到,我仍然得到同样的问题。如果重要的话,我使用的是Windows 8三星ATIV Smart PC并使用键盘底座。
Again, I tried every method of getting the arrow key press that I could find, and I keep getting the same problem. If it matters, I'm on a Windows 8 Samsung ATIV Smart PC and using the keyboard dock.
感谢您提供任何帮助。
Thanks in advance for any help.
推荐答案
#include <conio.h>
#include <iostream>
using namespace std;
#define KEY_UP 72
#define KEY_DOWN 80
#define KEY_LEFT 75
#define KEY_RIGHT 77
int main()
{
int c = 0;
while(1)
{
c = 0;
switch((c=getch())) {
case KEY_UP:
cout << endl << "Up" << endl;//key up
break;
case KEY_DOWN:
cout << endl << "Down" << endl; // key down
break;
case KEY_LEFT:
cout << endl << "Left" << endl; // key left
break;
case KEY_RIGHT:
cout << endl << "Right" << endl; // key right
break;
default:
cout << endl << "null" << endl; // not arrow
break;
}
}
return 0;
}
输出如下:
Up
Down
Right
Left
Up
Left
Right
Right
Up
检测到箭头键按!
这篇关于C ++当用户按箭头键时检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!