【问题标题】:C# - Rewrite/edit line while program is runningC# - 程序运行时重写/编辑行
【发布时间】:2015-12-22 20:32:33
【问题描述】:

有什么方法可以编辑/重写已经由 Console.PrintLine() 方法打印的某些行?我必须能够编辑提示中显示的任何行。

这是我尝试运行的代码的示例,可能看起来像:

public static void RewriteLine(LineNr, Text)
{
    //Code
}

Console.WriteLine("Text to be rewritten");
Console.Writeline("Just some text");
RewriteLine(1, "New text");

根据前面代码的输出显示我想要重写哪一行的示例:

要重写的文本 //这一行(已经被Console.WriteLine()方法执行的bin)替换为:“新文本”

只是一些文字

【问题讨论】:

  • 您在问如何在程序运行时更改源代码?听起来您需要使用变量并以编程方式设置这些变量的值之前显示它们。
  • @DStanley,我想他想用“新文本”覆盖输出的第一行——也就是说,能够在控制台窗口的任意位置写入。
  • 有一些“hacky”方法可以做到这一点......请参见此处:stackoverflow.com/questions/888533/…
  • @DStanley 不...我在问如何更改 Console.WriteLine() 方法显示的文本。但是在文本执行完 bin 之后。我知道如何删除某些行,但不知道如何用其他文本替换它。
  • 现在更混乱了。

标签: c# console-application edit prompt


【解决方案1】:

应该是这样的:

public static void RewriteLine(int lineNumber, String newText)
{
    int currentLineCursor = Console.CursorTop;
    Console.SetCursorPosition(0, currentLineCursor - lineNumber);
    Console.Write(newText); Console.WriteLine(new string(' ', Console.WindowWidth - newText.Length)); 
    Console.SetCursorPosition(0, currentLineCursor);
}

static void Main(string[] args)
{
    Console.WriteLine("Text to be rewritten");
    Console.WriteLine("Just some text");
    RewriteLine(2, "New text");
}

发生的事情是你改变了光标位置并在那里写了一些东西。您应该添加一些处理长字符串的代码。

【讨论】:

    猜你喜欢
    • 2012-03-20
    • 2019-02-13
    • 2011-07-01
    • 2018-12-31
    • 2015-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-24
    相关资源
    最近更新 更多