编程语言
首页 > 编程语言> > c# – 在读取Console行时听ESC

c# – 在读取Console行时听ESC

作者:互联网

我想将用户输入读入一个字符串,同时仍然可以随时在ESC按下,但是没有定义系统范围的热键.

所以当用户键入e时. G. “测试名称”但不是用ENTER确认按ESC,他应该被带回主菜单.

Console.Write("Enter name: ")
if (Console.ReadLine().Contains(ConsoleKey.Escape.ToString()))
{
    goto MainMenu;
}
return Console.ReadLine();

这是我能想到的最简单的方法,但是由于Console.ReadLine()没有看到ESC,所以它不起作用.

在开始输入文本here之前按下ESC时发现了一种相当复杂的反应方式,但我希望它随时可以工作.

解决方法:

您可能不得不放弃使用ReadLine并使用ReadKey自行滚动:

static void Main(string[] args)
{
    Console.Clear();
    Console.Write("Enter your name and press ENTER.  (ESC to cancel): ");
    string name = readLineWithCancel();

    Console.WriteLine("\r\n{0}", name == null ? "Cancelled" : name);

    Console.ReadLine();
}

//Returns null if ESC key pressed during input.
private static string readLineWithCancel()
{
    string result = null;

    StringBuilder buffer = new StringBuilder();

    //The key is read passing true for the intercept argument to prevent
    //any characters from displaying when the Escape key is pressed.
    ConsoleKeyInfo info = Console.ReadKey(true);
    while (info.Key != ConsoleKey.Enter && info.Key != ConsoleKey.Escape)
    {
        Console.Write(info.KeyChar);
        buffer.Append(info.KeyChar);
        info = Console.ReadKey(true);
    } 

    if (info.Key == ConsoleKey.Enter)
    {
        result = buffer.ToString();
    }

    return result;
}

此代码不完整,可能需要工作以使其健壮,但它应该给你一些想法.

标签:c,readline,key,console,hotkeys
来源: https://codeday.me/bug/20190717/1489090.html