以下代码实现对接收字符的 实时检验:
1 #region VaName 2 UI Ui = new UI(); 3 ConsoleKeyInfo cki = new ConsoleKeyInfo(); 4 public string VanName(int x, int y) 5 { 6 string name = ""; 7 Console.SetCursorPosition(x, y); 8 do 9 { 10 cki = Console.ReadKey(true); 11 if (cki.Key == ConsoleKey.Enter) 12 { 13 break; 14 } 15 if (cki.Key == ConsoleKey.Backspace) 16 { 17 if (Console.CursorLeft > x) 18 { 19 Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop); 20 Console.Write(" "); 21 Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop); 22 if (name.Length != 0) 23 { 24 name = name.Substring(0, name.Length - 1); 25 } 26 } 27 } 28 29 else if (cki.Key == ConsoleKey.Escape) 30 { 31 //Ui.Index(); 32 Environment.Exit(0); 33 } 34 else 35 { 36 Console.Write(cki.KeyChar.ToString()); 37 if (name.Length <= 5) 38 { 39 name = name + cki.KeyChar.ToString(); 40 } 41 else 42 { 43 Console.SetCursorPosition(x + 8, Console.CursorTop); 44 Console.ForegroundColor = ConsoleColor.Yellow; 45 Console.WriteLine("输入有误"); 46 Thread.Sleep(1000); 47 Console.SetCursorPosition(x + 8, y); 48 Console.WriteLine(" "); 49 Console.ForegroundColor = ConsoleColor.White; 50 Console.SetCursorPosition(x, y); 51 for (int i = 0; i <= name.Length; i++) 52 { 53 Console.Write(" "); 54 } 55 name = ""; 56 Console.SetCursorPosition(x, y); 57 //return CheckPwd(x,y,"ischeckpwd" ); 58 } 59 } 60 61 } while (cki.Key != ConsoleKey.Enter); 62 return name.Trim(); 63 } 64 #endregion VaName
控制台输入 并实时检验:
1 Console.SetCursorPosition(24, 5); 2 Console.WriteLine("姓 名: (只能为汉字)"); 3 string name = va.VaData(34, 5 );//验证姓名
由与cki 一次接收的是1个字符,而一个中文是占用2个字符,输入中文是下面返回的是乱码: Console.Write(cki.KeyChar.ToString());
如何才能实现标题的要求?