C# Console - hide the input from console window while typing

后端 未结 5 2004
被撕碎了的回忆
被撕碎了的回忆 2021-01-01 18:56

I\'m using Console.ReadLineto read the input of the user. However, I want to hide/exclude the inputted text on the console screen while typing. For example, whe

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-01 19:48

    private static string GetPassword()
        {
            StringBuilder input = new StringBuilder();
            while (true)
            {
                int x = Console.CursorLeft;
                int y = Console.CursorTop;
                ConsoleKeyInfo key = Console.ReadKey(true);
                if (key.Key == ConsoleKey.Enter)
                {
                    Console.WriteLine();
                    break;
                }
                if (key.Key == ConsoleKey.Backspace && input.Length > 0)
                {
                    input.Remove(input.Length - 1, 1);
                    Console.SetCursorPosition(x - 1, y);
                    Console.Write(" ");
                    Console.SetCursorPosition(x - 1, y);
                }
                else if (key.Key != ConsoleKey.Backspace)
                {
                    input.Append(key.KeyChar);
                    Console.Write("*");
                }
            }
            return input.ToString();
        }
    

提交回复
热议问题