清除最后一行,并在控制台应用程序中替换它?

时间:2018-04-24 18:06:13

标签: c# .net

我已经看过几次这个问题,但我访问过的问题对我来说没有一个可靠的答案。我在下面写了一个虚拟应用程序只是为了试一试,我注意到它有一些问题。

它将用列表中的下一行替换新行,问题是如果前一行比新行长,您仍然可以看到上一行的结尾。

如果您运行下面的代码,那么当它应该在How would did your new hat cost?的行上写一些内容时会看到这一点,但是会写出更像How would did your new hat cost?it?的内容,其中包含前一行的结尾

static void Main(string[] args)
{
    Console.CursorVisible = false;
    Console.WriteLine();

    var myLines = new List<string>
    {
        "I like dogs, but not cats.",
        "Want to get an icecream tomorrow?",
        "I would like to go to the park.",
        "If I was arrested, would you visit?",
        "How much did your new hat cost?"
    };

    foreach (var line in myLines)
    {
        Console.WriteLine($"  [{DateTime.Now.ToShortTimeString()}] Processing: " + line);
        Console.SetCursorPosition(0, Console.CursorTop - 1);
        Thread.Sleep(new Random().Next(200, 900));
    }

    Console.ReadKey(true);
}

1 个答案:

答案 0 :(得分:1)

将foreach循环修改为如下所示:

 foreach (var line in myLines)
        {
            Console.SetCursorPosition(0, Console.CursorTop - 1);
            ClearCurrentConsoleLine();
            Console.WriteLine($"  [{DateTime.Now.ToShortTimeString()}] Processing: " + line);
            Thread.Sleep(new Random().Next(200, 900));
        }

并使用以下方法:

public static void ClearCurrentConsoleLine()
    {
        int currentLineCursor = Console.CursorTop;
        Console.SetCursorPosition(0, Console.CursorTop);
        Console.Write(new string(' ', Console.WindowWidth));
        Console.SetCursorPosition(0, currentLineCursor);
    }

我已经习惯了以下方法来实现这个解决方案: Can Console.Clear be used to only clear a line instead of whole console?