保持Console.ReadLine总是在最后一行 [英] Keep Console.ReadLine always on last line
问题描述
我有一个用C#编写的应用程序,它通过while(true)循环和Console.ReadLine连续地从用户发出命令。
I have an application written in C# which takes continuously commands from the user via a while(true) loop and Console.ReadLine.
我也有各种背景操作通过控制台报告。查看这个简单的例子:
I also do have various background operations which report back via the console. View this simple example:
class Program
{
static void Main(string[] args)
{
new Messager(1000 * 2.5f);
new Messager(1000 * 3);
while (true)
{
Console.ReadLine();
}
}
}
public class Messager
{
Timer Timer;
public Messager(double interval)
{
this.Timer = new Timer(interval);
this.Timer.Elapsed += (sender, e) =>
{
Console.WriteLine("message from " + this.Timer.Interval);
};
this.Timer.Start();
}
}
问题是,当我输入命令和Messager在我按下Enter之前报告回来Messager中的消息将被追加到当前行,光标将被放置到下一行。请参阅以下屏幕截图:
The problem is, when I enter a command and a Messager reports back before I have pressed Enter the message from the Messager will be appended to my current line and the cursor will be placed into the next line. See this screenshot:
你猜想我不想那样。我想要一个命令的当前输入总是保持在最后一行,并且所有的消息都放在该行的上面。正如你从这样的应用程序所期望的。
As you'd guess I don't want that. I want the current inputting of a command to remain always in the last line and have all the messages coming placed above that line. Just as you'd expect from such an application. How do I achieve that?
推荐答案
这是我的问题的答案:
class Program
{
static void Main(string[] args)
{
new Messager(1000 * 2.5f);
new Messager(1000 * 3);
while (true)
{
Console.ReadLine();
}
}
}
public class Messager
{
Timer Timer;
public Messager(double interval)
{
this.Timer = new Timer(interval);
this.Timer.Elapsed += (sender, e) =>
{
int currentTopCursor = Console.CursorTop;
int currentLeftCursor = Console.CursorLeft;
Console.MoveBufferArea(0, currentTopCursor, Console.WindowWidth, 1, 0, currentTopCursor + 1);
Console.CursorTop = currentTopCursor;
Console.CursorLeft = 0;
Console.WriteLine("message from " + this.Timer.Interval);
Console.CursorTop = currentTopCursor +1;
Console.CursorLeft = currentLeftCursor;
};
this.Timer.Start();
}
}
这篇关于保持Console.ReadLine总是在最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!