Home > Net >  Is there a way to get an input in the console without having to press the enter key?
Is there a way to get an input in the console without having to press the enter key?

Time:08-17

I want to be able to get single characters from the console without having to press the enter key.

For example, when I press the letter "e", I want to immediately use that value without the user having to press the enter key

CodePudding user response:

Try:

var key = System.Console.ReadKey(intercept: true);

The intercept flag prevents the pressed key from being rendered into the terminal.

CodePudding user response:

Hope this is what you are looking for!
Reference: How to handle key press event in console application

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Press 'Shift Q' to exit.");
            do {
                ConsoleKeyInfo keyInfo = Console.ReadKey();
                if (keyInfo.Modifiers.HasFlag(ConsoleModifiers.Shift)
                    && keyInfo.Key == ConsoleKey.Q)
                {
                    break;
                }

                // TODO : Write your code here
                Console.WriteLine(keyInfo.KeyChar);
            } while (true);
        }
    }
}

CodePudding user response:

What yoy need is Console.ReadKey().

For example:

 ConsoleKeyInfo key = Console.ReadKey(); // Read pressed key
 char c = key.KeyChar; // char...
 string s = c.ToString(); // ... or string, depending on what you need.

As already suggested, you can try type Console. in VS and see which members are available.

  •  Tags:  
  • c#
  • Related