C#控制台输入密码星号显示


在Program类中的Main方法里:

 1 public class Program
 2 {
 3     static void Main(string[] args)
 4     {
 5         Console.WriteLine("是否要结束程序,取消请输入'No', 确认请输入密码:");
 6 
 7         string passwordInput = null;
 8         bool readPassword = true;
 9 
10         while (readPassword)
11         {
12             while (true)
13             {
14                 #region 控制台输入密码星号显示
15 
16                 ConsoleKeyInfo ck = Console.ReadKey(true);
17 
18                 //判断用户是否按下的Enter键
19                 if (ck.Key != ConsoleKey.Enter)
20                 {
21                     if (ck.Key != ConsoleKey.Backspace)
22                     {
23                         //将用户输入的字符存入字符串中
24                         passwordInput += ck.KeyChar.ToString();
25                         //将用户输入的字符替换为*
26                         Console.Write("*");
27                     }
28                     else
29                     {
30                         //删除错误的字符
31                         Console.Write("\b \b");
32                     }
33                 }
34                 else
35                 {
36                     Console.WriteLine();
37                     break;
38                 }
39 
40                 #endregion
41             }
42 
43             if (passwordInput == "123456")
44             {
45                 readPassword = false;
46                 Console.WriteLine("密码正确");
47             }
48             else
49             {
50                 Console.WriteLine("密码有误,请重新输入");
51                 passwordInput = null;
52                 readPassword = true;
53             }
54         }
55     }
56 }

 

参考:C#_控制台输入密码星号显示

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM