简体   繁体   English

如何在 C# 中从键盘上获取键

[英]How to catch key from keyboard in C#

I have a problem.我有个问题。 I need write a C# program Input: Allows the user to enter multiple lines of text, press Ctrl + Enter to finish typing Output: Standardize by, rearranging lines in the right order of increasing time.我需要编写一个 C# 程序 输入:允许用户输入多行文本,按 Ctrl + Enter 完成输入 Output:标准化,按时间增加的正确顺序重新排列行。

I was tried but I don't know how to catch Ctrl + Enter from keyboard:我试过了,但我不知道如何从键盘捕捉 Ctrl + Enter:

I expect the output like Example:我希望 output 像示例:

“Created at 28/02/2018 10:15:35 AM by Andy.
Updated at 03/03/2018 02:45:10 PM by Mark
Clear name at 02/03/2018 11:34:05 AM by Andy”

DateTime is needed rearranging DateTime 需要重新排列

You need to create your own input system to override the default console handler.您需要创建自己的输入系统来覆盖默认的控制台处理程序。

You will create a loop to ReadKey(true) and process all desired key codes like arrows, backspace, delete, letters, numbers, and the Ctrl+Enter...您将创建一个ReadKey(true)循环并处理所有需要的键代码,如箭头、退格、删除、字母、数字和 Ctrl+Enter...

So for each key, you reinject to the console what you want to process, moving the caret, deleting char, and ending the process.因此,对于每个键,您将要处理的内容重新注入控制台,移动插入符号,删除字符并结束该过程。

You need to manage the result buffer as well.您还需要管理结果缓冲区。

That's fun.这很有趣。

.NET Console Class .NET 控制台 Class

Here is a sample:这是一个示例:

void GetConsoleUserInput()
{
  Console.WriteLine("Enter something:");
  var result = new List<char>();
  int index = 0;
  while ( true )
  {
    var input = Console.ReadKey(true);
    if ( input.Modifiers.HasFlag(ConsoleModifiers.Control) 
      && input.Key.HasFlag(ConsoleKey.Enter) )
      break;
    if ( char.IsLetterOrDigit(input.KeyChar) )
    {
      if (index == result.Count)
        result.Insert(index++, input.KeyChar);
      else
        result[index] = input.KeyChar;
      Console.Write(input.KeyChar);
    }
    else
    if ( input.Key == ConsoleKey.LeftArrow && index > 0 )
    {
      index--;
      Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
    }
    // And so on
  }
  Console.WriteLine();
  Console.WriteLine("You entered: ");
  Console.WriteLine(String.Concat(result));
  Console.WriteLine();
  Console.ReadKey();
}

For multiline, the result buffer and index can be:对于多行,结果缓冲区和索引可以是:

var result = new Dictionary<int, List<char>>();

And instead of index you can use:而不是索引,您可以使用:

int posX;
int posY;

So that is:那就是:

result[posY][posX];

Don't forget to update posX matching the line length when using up and down arrows.使用向上和向下箭头时,不要忘记更新匹配行长的 posX。

Where it gets complicated, it's the management of the width of the console and the wrapping...它变得复杂的地方是控制台宽度和包装的管理......

Have a great job!有一个伟大的工作!

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

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