Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

c - How can I distinguish two keystrokes which have similar responses from getch()

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
");
            break;
           /*Some other stuff*/
            }
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).

From MSDN:

The _getch and _getwch functions read a single character from the console without echoing the character. None of these functions can be used to read CTRL+C. When reading a function key or an arrow key, each function must be called twice; the first call returns 0 or 0xE0, and the second call returns the actual key code.

So you need to check for a 0 or 0xE0 which tells you the next character is a key code, not an ASCII code.

The list of key codes: https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx

EDIT:

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.

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) {
    ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...