How to catch key from keyboard in C#

安稳与你 提交于 2021-02-05 10:43:05

问题


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.

I was tried but I don't know how to catch Ctrl + Enter from keyboard:

I expect the output like Example:

“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


回答1:


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

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

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.

Where it gets complicated, it's the management of the width of the console and the wrapping...

Have a great job!



来源:https://stackoverflow.com/questions/58109201/how-to-catch-key-from-keyboard-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!