简体   繁体   中英

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.

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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