How to use keyboards function with _getch(), as it

2019-03-07 01:24发布

问题:

My problem is that I want to do a special thing when my user is pushing tabulation in the terminal. My first code explains that :

char buffer[100];

while (true)
{
    std::cin.getline(buffer, 100); // do IMMEDIATELY something if 'tabulation' was used ?

}

So I asked myself how to check every chars ? I tried with _getch();

while (true)
{
    c = _getch();

    if (c == '\t')
        // do something special
    else
        std::cout << (char)c;
}

But now, I can't use any specials functions keys as arrows, del, suppr, etc... I can't move into what am I typing as I can with getline()

So is there any solutions to do a special interruption in a middle of a getline() ? Or is it possible to use _getch() in a different way ? I also tried to do an other thread (one with getline() and the other with _getch() for checking every ) but I'm not so sure about what I can do with threads.

It could be possible to handle every special function (arrows keys, del, suppr, etc...) 'manually' but I'm looking for another solution.

回答1:

Assuming you mean the _getch() function from the Microsoft C runtime library:

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, if _getch() returns either 0 or 0xE0 (224), you'll have to call the function again to see which specific key was pressed.

At least on my machine, these “extended” character codes are as follows (in decimal):

  • 0 59 = F1
  • 0 60 = F2
  • 0 61 = F3
  • 0 62 = F4
  • 0 63 = F5
  • 0 64 = F6
  • 0 65 = F7
  • 0 66 = F8
  • 0 67 = F9
  • 0 68 = F10
  • 224 71 = Home
  • 224 72 = ↑ (up arrow)
  • 224 73 = Page Up
  • 224 75 = ← (left arrow)
  • 224 77 = → (right arrow)
  • 224 79 = End
  • 224 80 = ↓ (down arrow)
  • 224 81 = Page Down
  • 224 82 = Insert
  • 224 83 = Delete
  • 224 133 = F11
  • 224 134 = F12

As for what to do with these codes, take a look at SetConsoleCursorPosition and related console API functions.