I\'m using Console.ReadLine
to read the input of the user. However, I want to hide/exclude the inputted text on the console screen while typing. For example, whe
Console.ReadKey(true) hides the user key. I do not believe Console.Read() offers such a capability. If necessary you can sit in a loop reading keys one at a time until enter is pressed. See this link for an example.
I created this method from the code in the answer by dataCore and the suggestion by m4tt1mus. I also added support for the backspace key.
private static string GetHiddenConsoleInput()
{
StringBuilder input = new StringBuilder();
while (true)
{
var key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter) break;
if (key.Key == ConsoleKey.Backspace && input.Length > 0) input.Remove(input.Length - 1, 1);
else if (key.Key != ConsoleKey.Backspace) input.Append(key.KeyChar);
}
return input.ToString();
}
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();
}
Here is a short implementation. thx @ojblass for the idea
System.Console.Write("password: ");
string password = null;
while (true)
{
var key = System.Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter)
break;
password += key.KeyChar;
}
I just changed the foreground colour to black while the password was being inputted. I a newbie so it's probably a bad idea but it worked for the challenge i was trying
Console.WriteLine("Welcome to our system. Please create a UserName");
var userName = Console.ReadLine();
Console.WriteLine("Now please create a password");
Console.ForegroundColor = ConsoleColor.Black;
var password = Console.ReadLine();
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Okay, let's get you logged in:");