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