密码屏蔽控制台应用程序

我尝试了以下代码...


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

但是这种方式在输入密码时不能使用退格功能。有什么建议吗?


白衣染霜花
浏览 371回答 3
3回答

杨魅力

为此,您应该使用System.Security.SecureStringpublic SecureString GetPassword(){    var pwd = new SecureString();    while (true)    {        ConsoleKeyInfo i = Console.ReadKey(true);        if (i.Key == ConsoleKey.Enter)        {            break;        }        else if (i.Key == ConsoleKey.Backspace)        {            if (pwd.Length > 0)            {                pwd.RemoveAt(pwd.Length - 1);                Console.Write("\b \b");            }        }        else if (i.KeyChar != '\u0000' ) // KeyChar == '\u0000' if the key pressed does not correspond to a printable character, e.g. F1, Pause-Break, etc        {            pwd.AppendChar(i.KeyChar);            Console.Write("*");        }    }    return pwd;}
打开App,查看更多内容
随时随地看视频慕课网APP