本文介绍了当按下一个键时,如何中断(不使用线程)console.readline?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我解释一下,这是我想要实现的:

Let me explain, this is what I'm trying to achieve:

Enter name:
F4-Quit

是有办法显示下一行
显示之前?原因是我想要,在任何时候退出,即使名字还没有输入(光标在等待),这是非常有用的,在许多情况下,有人在进入信息过程中改变主意,想要退出或回去

is there a way to display the next line (F4-Quit) without readline waiting for user inputbefore displaying it? the reason is I wanted to, at anytime quit, even though name has not been entered yet (cursor is waiting), this is very useful in many circumstances where someone during the process of entering information changes their mind and wants to quit or go back.

如果不可能的话,会是什么呢?

If that's not possible what would be the way around it?

谢谢!

推荐答案

只需编写您自己的ReadLine()版本。这是一个TryReadLine()版本的.NET的TryParse()模式:

Just write your own version of ReadLine(). Here's a TryReadLine() version in the pattern of .NET's TryParse():

    static bool TryReadLine(out string result) {
        var buf = new StringBuilder();
        for (; ; ) {
            var key = Console.ReadKey(true);
            if (key.Key == ConsoleKey.F4) {
                result = "";
                return false;
            }
            else if (key.Key == ConsoleKey.Enter) {
                result = buf.ToString();
                return true;
            }
            else if (key.Key == ConsoleKey.Backspace && buf.Length > 0) {
                buf.Remove(buf.Length - 1, 1);
                Console.Write("\b \b");
            }
            else if (key.KeyChar != 0) {
                buf.Append(key.KeyChar);
                Console.Write(key.KeyChar);
            }
        }
    }

这篇关于当按下一个键时,如何中断(不使用线程)console.readline?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 07:04