控制台的实时键盘输入(在 Windows 中)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7519039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 18:08:11  来源:igfitidea点击:

Real-time keyboard input to console (in Windows)?

c++windowsinput

提问by SSight3

I have a doubly-linked list class, where I want to add characters to the list as the user types them, or removes the last node in the list each time the user presses backspace, whilst displaying the results in console in real-time.

我有一个双向链接列表类,我想在用户键入字符时将字符添加到列表中,或者每次用户按退格键时删除列表中的最后一个节点,同时在控制台中实时显示结果。

What functions would I use to intercept individual keyboard input, and display it in real-time to the console? So the following results:

我将使用哪些功能来拦截单个键盘输入,并将其实时显示到控制台?所以结果如下:

User starts typing:

用户开始输入:

Typ_

类型_

User stops typing:

用户停止输入:

Typing this on screen_

在屏幕上打字_

User presses backspace 5 times:

用户按退格键 5 次:

Typing this on s_

在 s_ 上打字

Particular OS is windows (vista, more specifically).

特定的操作系统是 windows(更具体地说是 vista)。

As a side-note GetAsyncKeyState under windows.h appears to perhaps be for keyboard input, however the issue of real-time display of the console remains.

作为旁注,windows.h 下的 GetAsyncKeyState 似乎可能用于键盘输入,但是控制台的实时显示问题仍然存在。

采纳答案by SChepurin

You will be surprised, but this code will do what you want:

你会感到惊讶,但这段代码会做你想做的:

/* getchar example : typewriter */
#include <stdio.h>

int main ()
{
  char c;
  puts ("Enter text. Include a dot ('.') in a sentence to exit:");
  do {
    c=getchar();
    putchar (c);
  } while (c != '.');
  return 0;
}

回答by Kerrek SB

C++ has no notion of a "keyboard". It only has an opaque FILE called "stdin" from which you can read. However, the content of that "file" is populated by your environment, specifically by your terminal.

C++ 没有“键盘”的概念。它只有一个名为“stdin”的不透明文件,您可以从中读取。但是,该“文件”的内容由您的环境填充,特别是由您的终端填充。

Most terminals buffer the input line before sending it to the attached process, so you never get to see the existence of backspaces. What you really need is to take control of the terminal directly.

大多数终端在将输入行发送到附加进程之前会对其进行缓冲,因此您永远不会看到退格符的存在。您真正需要的是直接控制终端。

This is a very platform-dependent procedure, and you have to specify your platform if you like specific advice. On Linux, try ncursesor termios.

这是一个非常依赖于平台的过程,如果您喜欢特定的建议,则必须指定您的平台。在 Linux 上,尝试ncursestermios

回答by ixe013

You could use ReadConsoleInput, adding incoming caracters to your list, look for the backspace keys (INPUT_RECORD->KEY_EVENT_RECORD.wVirtualScanCode == VK_BACKSPACE) and removing the last caracter from your list for all of them.

您可以使用ReadConsoleInput,将传入的字符添加到列表中,查找退格键(INPUT_RECORD->KEY_EVENT_RECORD.wVirtualScanCode == VK_BACKSPACE)并从列表中删除所有字符的最后一个字符。