如题,请问一下诸位高手,Console.ReadKey按下的键会显示在控制台窗口上,但是按backspace却无法删除回退,怎么解决?
1 public string ReadLine()
2 {
3 string ReadString = "";
4 while (true)
5 {
6 ConsoleKey InputKey = Console.ReadKey().Key;
7 if (InputKey != ConsoleKey.Enter)
8 {
9 if (InputKey == ConsoleKey.Backspace)
10 {
11 if (ReadString != "")
12 {
13 ReadString = ReadString.Substring(0, ReadString.Length - 1);
14 }
15 }
16 else
17 {
18 ReadString = ReadString + ((char)InputKey.GetHashCode()).ToString();
19 }
20 }
21 else
22 {
23 break;
24 }
25
26 if (InputKey == ConsoleKey.Escape)
27 {
28 ReadString = "ESC";
29 break;
30 }
31 }
32
33 return ReadString;
34 }
初始化string ReadString = ""了 所以if (ReadString != "") 总是为false
@john23.net: 如果想實現 backspace退格,應該是判斷接受的readkey()值爛定位光標.
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string ReadString = "";
Console.WriteLine("445664564sdfasfas");
int x = Console.CursorLeft;
int y = Console.CursorTop;
while (true)
{
ConsoleKey InputKey = Console.ReadKey().Key;
if (InputKey != ConsoleKey.Enter)
{
if (InputKey == ConsoleKey.Backspace)
{
if (ReadString != "")
{
ReadString = ReadString.Substring(0, ReadString.Length - 1);
Console.SetCursorPosition(x, y);
Console.Write(ReadString+" ");
}
}
else
{
ReadString = ReadString + ((char)InputKey.GetHashCode()).ToString();
}
}
else
{
break;
}
if (InputKey == ConsoleKey.Escape)
{
ReadString = "ESC";
break;
}
}
Console.WriteLine(ReadString);
Console.ReadKey();
}
}
}
因为按的键被打印在控制台里,所以不能别删,如果是你输入的则可以删。
谢谢楼主分享;学习了