简体   繁体   English

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

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

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_ 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似乎可能用于键盘输入,但是控制台的实时显示问题仍然存在。

C++ has no notion of a "keyboard". C ++没有“键盘”的概念。 It only has an opaque FILE called "stdin" from which you can read. 它只有一个名为“stdin”的不透明FILE,您可以从中读取。 However, the content of that "file" is populated by your environment, specifically by your terminal. 但是,该“文件”的内容由您的环境填充,特别是您的终端。

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 ncurses or termios . 在Linux上,尝试ncursestermios

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

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM