我尝试了下面的代码…

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

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


当前回答

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

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

其他回答

我在shermy的香草c# 3.5 . net解决方案中发现了一个bug,否则它会很有魅力。我还结合了Damian leszczyzynski - Vash的SecureString思想,但如果你喜欢,你可以使用普通字符串。

错误:如果在密码提示期间按退格键,并且当前密码长度为0,则在密码掩码中错误地插入了星号。要修复此错误,请修改以下方法。

    public static string ReadPassword(char mask)
    {
        const int ENTER = 13, BACKSP = 8, CTRLBACKSP = 127;
        int[] FILTERED = { 0, 27, 9, 10 /*, 32 space, if you care */ }; // const


        SecureString securePass = new SecureString();

        char chr = (char)0;

        while ((chr = System.Console.ReadKey(true).KeyChar) != ENTER)
        {
            if (((chr == BACKSP) || (chr == CTRLBACKSP)) 
                && (securePass.Length > 0))
            {
                System.Console.Write("\b \b");
                securePass.RemoveAt(securePass.Length - 1);

            }
            // Don't append * when length is 0 and backspace is selected
            else if (((chr == BACKSP) || (chr == CTRLBACKSP)) && (securePass.Length == 0))
            {
            }

            // Don't append when a filtered char is detected
            else if (FILTERED.Count(x => chr == x) > 0)
            {
            }

            // Append and write * mask
            else
            {
                securePass.AppendChar(chr);
                System.Console.Write(mask);
            }
        }

        System.Console.WriteLine();
        IntPtr ptr = new IntPtr();
        ptr = Marshal.SecureStringToBSTR(securePass);
        string plainPass = Marshal.PtrToStringBSTR(ptr);
        Marshal.ZeroFreeBSTR(ptr);
        return plainPass;
    }

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

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

采取顶部的答案,以及从其评论的建议,并将其修改为使用SecureString而不是String,测试所有控制键,而不是错误或在密码长度为0时向屏幕写入额外的“*”,我的解决方案是:

public static SecureString getPasswordFromConsole(String displayMessage) {
    SecureString pass = new SecureString();
    Console.Write(displayMessage);
    ConsoleKeyInfo key;

    do {
        key = Console.ReadKey(true);

        // Backspace Should Not Work
        if (!char.IsControl(key.KeyChar)) {
            pass.AppendChar(key.KeyChar);
            Console.Write("*");
        } else {
            if (key.Key == ConsoleKey.Backspace && pass.Length > 0) {
                pass.RemoveAt(pass.Length - 1);
                Console.Write("\b \b");
            }
        }
    }
    // Stops Receving Keys Once Enter is Pressed
    while (key.Key != ConsoleKey.Enter);
    return pass;
}

控制台。写(“b \ b \”);将从屏幕上删除星号字符,但在else块中没有任何代码可以从传递字符串变量中删除先前输入的字符。

这里是相关的工作代码,应该做你需要的:

var pass = string.Empty;
ConsoleKey key;
do
{
    var keyInfo = Console.ReadKey(intercept: true);
    key = keyInfo.Key;

    if (key == ConsoleKey.Backspace && pass.Length > 0)
    {
        Console.Write("\b \b");
        pass = pass[0..^1];
    }
    else if (!char.IsControl(keyInfo.KeyChar))
    {
        Console.Write("*");
        pass += keyInfo.KeyChar;
    }
} while (key != ConsoleKey.Enter);

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

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