密码屏蔽控制台应用程序 [英] Password masking console application

查看:142
本文介绍了密码屏蔽控制台应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试以下code ...

I tried the following code...

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

不过,这种方式同时输入密码的回退功能不起作用。
任何建议?

But this way the backspace functionality doesn't work while typing the password. Any suggestion?

推荐答案

Console.Write(\\ B \\ B); 将从屏幕中删除星号字符,但你没有你的其他块中的任何code,消除pviously从通过字符串变量。

Console.Write("\b \b"); will delete the asterisk character from the screen, but you do not have any code within your else block that removes the previously entered character from your pass string variable.

下面是有关的code部分(的if..else 部分)应您要求什么:

Here's the relevant code portion (the if..else section) that should do what you require:

// Backspace Should Not Work
if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
{
   pass += key.KeyChar;
   Console.Write("*");
}
else
{
   if (key.Key == ConsoleKey.Backspace && pass.Length > 0)
   {
      pass = pass.Substring(0, (pass.Length - 1));
      Console.Write("\b \b");
   }
}

这篇关于密码屏蔽控制台应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆