How to catch key from keyboard in C#

前端 未结 1 528
醉酒成梦
醉酒成梦 2021-01-29 04:23

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 lin

1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-29 05:02

    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();
      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>();
    

    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!

    0 讨论(0)
提交回复
热议问题