问题描述
正如我在标题中所说,如何区分两个与 getch() 响应相似的击键.在这个代码块中,K 和左箭头键的 getch() 响应是相同的,所以当我输入大写 k case 75 时.我该如何解决?我也遇到了其他一些词的问题.
As I said in title, How can I distinguish two keystrokes which have similar responses from getch(). In this code block, K's and left arrow key's getch() responses are same, so when I type capital k case 75 works. How can I fix it? Also I got this problem with some other words.
while(1){
ch1=getch();
switch( ch2 = getch())
{
if(ch1 != 0xE0)
{
default:
for(i=' ';i<'}';i++)
{
if(i == ch2)
{
/*SOME STUFF*/
printf("%c" , iter->x);
}
break;
}
else
{
case 72: printf("UP WAS PRESSED\n");
break;
/*Some other stuff*/
}
}
}
推荐答案
当按下左箭头等特殊字符时,getch
将首先返回值 0 或 0xE0,然后它会返回一个键码(与 ASCII 码不同).
When a special character such as left-arrow is pressed, getch
will first return either the value 0 or 0xE0, then it will return a key code (which is not the same as an ASCII code).
来自 MSDN:
_getch
和 _getwch
函数从控制台而不回显字符.这些功能都不能用于阅读CTRL+C.读取功能键或箭头键时,每个函数必须被调用两次;第一次调用返回 0 或 0xE0,并且第二个调用返回实际的键码.
因此您需要检查 0 或 0xE0 是否告诉您下一个字符是键码,而不是 ASCII 码.
So you need to check for a 0 or 0xE0 which tells you the next character is a key code, not an ASCII code.
键码列表:https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
你的 if(ch1 != 0xE0)
不在任何 case
之外,所以它会被跳过.此外,当您进入循环时,您总是会调用 getch
两次.因此,如果您没有获得关键代码,您最终会阅读 2 个常规字符,并且很可能会跳过其中一个.
Your if(ch1 != 0xE0)
is outside of any case
, so it gets skipped over. Also, you're always calling getch
twice when you enter the loop. So if you didn't get a key code, you end up reading 2 regular characters and most likely skip one of them.
使用单个 getch
开始循环.然后检查 0 或 0xE0,如果找到则再次调用 getch
.
Start you loop with a single getch
. Then check for 0 or 0xE0, and if found then call getch
again.
while (1) {
int ch = getch();
int keycode = 0;
if (ch == 0 || ch == 0xe0) {
keycode = 1;
ch = getch();
}
switch (ch) {
...
这篇关于如何从 getch() 区分两个具有相似响应的击键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!