首页新闻找找看学习计划

C# 控制台程序Console.ReadKey的用法

1
悬赏园豆:20 [待解决问题]

如题,请问一下诸位高手,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 }
问题补充: 也就是刷新控制台的输出
candyjun的主页 candyjun | 初学一级 | 园豆:180
提问于:2011-04-20 14:04
< >
分享
所有回答(4)
0

初始化string ReadString = ""了 所以if (ReadString != "") 总是为false

john23.net | 园豆:930 (小虾三级) | 2011-04-20 15:00
初始化ReadString是在while死循环的外面,所以不会总是为false啊
支持(0) 反对(0) candyjun | 园豆:180 (初学一级) | 2011-04-20 15:09
按了backspace后方法没返回啊,你的ReadString没返回啊
支持(0) 反对(0) john23.net | 园豆:930 (小虾三级) | 2011-04-20 15:21
@candyjun:按了backspace后方法没返回啊,你的ReadString没返回啊
支持(0) 反对(0) john23.net | 园豆:930 (小虾三级) | 2011-04-20 15:22

@john23.net: 如果想實現 backspace退格,應該是判斷接受的readkey()值爛定位光標.

支持(0) 反对(0) Cornelius | 园豆:78 (初学一级) | 2013-04-24 14:45
0
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();

}

}
}
萌浩 | 园豆:205 (菜鸟二级) | 2011-04-21 16:36
0

因为按的键被打印在控制台里,所以不能别删,如果是你输入的则可以删。

峰和日丽 | 园豆:110 (初学一级) | 2012-11-09 22:20
0

谢谢楼主分享;学习了

stream2011 | 园豆:202 (菜鸟二级) | 2013-09-22 17:59
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册