我尝试了下面的代码…

string pass = "";
Console.Write("Enter your password: ");
ConsoleKeyInfo key;

do
{
    key = Console.ReadKey(true);

    // Backspace Should Not Work
    if (key.Key != ConsoleKey.Backspace)
    {
        pass += key.KeyChar;
        Console.Write("*");
    }
    else
    {
        Console.Write("\b");
    }
}
// Stops Receving Keys Once Enter is Pressed
while (key.Key != ConsoleKey.Enter);

Console.WriteLine();
Console.WriteLine("The Password You entered is : " + pass);

但是这样的话,退格键在输入密码时就不起作用了。 任何建议吗?


当前回答

(我的)nuget包来做这个,基于上面的答案:

安装包PanoramicData。ConsoleExtensions

用法:

using PanoramicData.ConsoleExtensions;

...

Console.Write("Password: ");
var password = ConsolePlus.ReadPassword();
Console.WriteLine();

项目网址:https://github.com/panoramicdata/PanoramicData.ConsoleExtensions

欢迎拉请求。

其他回答

呀的家伙

    static string ReadPasswordLine()
    {
        string pass = "";
        ConsoleKeyInfo key;
        do
        {
            key = Console.ReadKey(true);
            if (key.Key != ConsoleKey.Enter)
            {
                if (!(key.KeyChar < ' '))
                {
                    pass += key.KeyChar;
                    Console.Write("*");
                }
                else if (key.Key == ConsoleKey.Backspace && pass.Length > 0)
                {
                    Console.Write(Convert.ToChar(ConsoleKey.Backspace));
                    pass = pass.Remove(pass.Length - 1);
                    Console.Write(" ");
                    Console.Write(Convert.ToChar(ConsoleKey.Backspace));
                }
            }
        } while (key.Key != ConsoleKey.Enter);
        return pass;
    }

我的忽略控制字符和处理行换行:

public static string ReadLineMasked(char mask = '*')
{
    var sb = new StringBuilder();
    ConsoleKeyInfo keyInfo;
    while ((keyInfo = Console.ReadKey(true)).Key != ConsoleKey.Enter)
    {
        if (!char.IsControl(keyInfo.KeyChar))
        {
            sb.Append(keyInfo.KeyChar);
            Console.Write(mask);
        }
        else if (keyInfo.Key == ConsoleKey.Backspace && sb.Length > 0)
        {
            sb.Remove(sb.Length - 1, 1);

            if (Console.CursorLeft == 0)
            {
                Console.SetCursorPosition(Console.BufferWidth - 1, Console.CursorTop - 1);
                Console.Write(' ');
                Console.SetCursorPosition(Console.BufferWidth - 1, Console.CursorTop - 1);
            }
            else Console.Write("\b \b");
        }
    }
    Console.WriteLine();
    return sb.ToString();
}

下面是一个版本,增加了对Escape键的支持(它返回一个空字符串)

public static string ReadPassword()
{
    string password = "";
    while (true)
    {
        ConsoleKeyInfo key = Console.ReadKey(true);
        switch (key.Key)
        {
            case ConsoleKey.Escape:
                return null;
            case ConsoleKey.Enter:
                return password;
            case ConsoleKey.Backspace:
                if (password.Length > 0) 
                {
                    password = password.Substring(0, (password.Length - 1));
                    Console.Write("\b \b");
                }
                break;
            default:
                password += key.KeyChar;
                Console.Write("*");
                break;
        }
    }
}

我只是改进代码从问我简单,只是工作

    string pass = ""; //create empty password string
    Console.Write("Enter your password: ");
    ConsoleKeyInfo key;
    int passLen = 0; // base password length

    do
    {
        key = Console.ReadKey(true); //reading keyboard key

        if (key.Key == ConsoleKey.Escape) Environment.Exit(0); // If key is escape console will close (optional)

        if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter) // on key with is not bacspase and enter 
        {
            pass += key.KeyChar; //password string add key value
            Console.Write("*"); // and print star as masked char 
            passLen++; // upgrading password length
        }
        else if (passLen > 0 && key.Key == ConsoleKey.Backspace) //if password have a any symbol and u press Backspace
        {   
                Console.Write("\b \b"); //Backspace delete star symbol and coursor back in line 
                passLen--; // password length is one less
                pass = pass[0..^1]; // new string passowrd is string without last charter 
        }
    } 
    while (key.Key != ConsoleKey.Enter); // if you press enter this stop execute with your password

    Console.WriteLine();
    Console.WriteLine("The Password You entered is : " + pass);

下面是我的简单版本。 每次你按下一个键,从控制台删除所有,并绘制尽可能多的'*'作为密码字符串的长度。

int chr = 0;
string pass = "";
const int ENTER = 13;
const int BS = 8;

do
{
   chr = Console.ReadKey().KeyChar;
   Console.Clear(); //imediately clear the char you printed

   //if the char is not 'return' or 'backspace' add it to pass string
   if (chr != ENTER && chr != BS) pass += (char)chr;

   //if you hit backspace remove last char from pass string
   if (chr == BS) pass = pass.Remove(pass.Length-1, 1);

   for (int i = 0; i < pass.Length; i++)
   {
      Console.Write('*');
   }
} 
 while (chr != ENTER);

Console.Write("\n");
Console.Write(pass);

Console.Read(); //just to see the pass