ESC键
问题描述:
我想:ESC键
while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape))
{
// do something
}
这不能帮助我并没有做什么,我需要.. 我的代码是:
Console.WriteLine("Please enter your Login Details:");
Console.Write("User Name: ");
string userName = Console.ReadLine();
Console.Write("Password: ");
string Password = Console.ReadLine();
if (cmd.Login(userName, Password))
{
// my rest of my code
}
我需要在任何console.readline()
如果我按下ESC去第一个代码或开始把用户名和密码... 我需要按ESC在我的应用程序它重新启动到第一阶段在任何时间和任何阶段..这可能吗?
答
Console.ReadKey()可用于侦听特定按键,例如Escape键。
您可能需要更改方法以使用Console.ReadLine()以外的方法读取用户名和密码输入。看到这个问题:Using ReadLine() and ReadKey() Simultaneously
答
简短的回答是,你不能这样做,如果你使用Console.Read
或Console.ReadLine
以获取输入。问题在于Read
和ReadLine
是阻止调用行编辑等的调用(退格,删除,左右移动等)。它是缓冲输入。唯一的出路就是按Enter键或杀死程序。 Read
和ReadLine
不做任何特殊的Escape处理。
我知道做你所要求的唯一方法是使用原始控制台I/O。也就是说,使用Console.ReadKey
来读取每个单独的键并显示它,并且还处理退格,行尾等。这是一个真正的脖子上的痛苦,很难得到正确的。
下面的代码接近你想要做的事情。基本上,如果用户输入名称或密码的空白值,那么它将回到顶部。 ESC键将清除一个字段。所以如果在密码提示符下输入“foO”然后点击ESC,该字段将被清空。然后他击中回车,并将他带回到开始处(即输入名称)。
这不完全是你要求的,但它可能是最好的,你会得到没有很多努力。
private void DoIt()
{
string name;
string pw;
bool done = false;
do
{
Console.WriteLine();
Console.WriteLine("LOGIN");
Console.WriteLine();
Console.Write("User name: ");
name = Console.ReadLine();
if (string.IsNullOrWhiteSpace(name))
{
continue;
}
Console.Write("Password: ");
pw = Console.ReadLine();
if (string.IsNullOrWhiteSpace(pw))
{
continue;
}
done = true;
} while (!done);
Console.WriteLine("Logging in ...");
}
的[侦听在.NET控制台应用程序按键]可能的复制(http://*.com/questions/5891538/listen-for-key-press-in-net-console-app) – KidCode
[检查这个问题!](http://*.com/questions/5891538/listen-for-key-press-in-net-console-app) – KidCode
阅读整个问题!他不问如何暂停,直到按下一个键。他问他如何在“Read”或“ReadLine”中捕获按键,这样如果用户按下ESC,“Read”将中止,并且可以跳回到登录过程的开始。 –