问题
I would like to fill/update the entire bottom line of the console. Example:
static void Main(string[] args)
{
Console.BufferWidth = Console.WindowWidth;
Console.BufferHeight = Console.WindowHeight;
Console.CursorTop = Console.WindowHeight - 1;
string s = "";
for(int i = 0; i < Console.BufferWidth; i++)
s += (i%10).ToString();
Console.Write(s);
Console.CursorTop = 0;
Console.ReadKey();
}
The issue is that when the text is printed, it moves to a new line. Similar questions stated to move the cursor to 0,0, however that only works when the buffer size is larger than the window size, and I would like the buffer width and the window width to be equal (to remove scroll bars). Any ideas? The closest I could get is printing to a higher line and moving it to the last line, however that will not be acceptable in the full project.
Edit: The last sentence of the question was specifically talking about movebufferarea. The reason why that won't work can be seen by this example:
static void Main(string[] args)
{
Console.BufferWidth = Console.WindowWidth;
Console.BufferHeight = Console.WindowHeight;
while (!Console.KeyAvailable)
{
Console.CursorTop = Console.WindowHeight - 2;
string s = "";
for (int i = 0; i < Console.BufferWidth; i++)
s += (i % 10).ToString();
Console.Write(s);
Console.MoveBufferArea(0, Console.WindowHeight - 2, Console.WindowWidth, 1, 0, Console.WindowHeight - 1);
Thread.Sleep(10);
}
}
The sentence will flicker every so often because it is printed first and then moved.
回答1:
Since the cursor is always trailing after the text you've written you can either write one less character to avoid going to the next line, or simply write the characters directly into the buffer (I believe, Console.MoveBufferArea can be used for that).
回答2:
As Joey mentioned, using the MoveBufferArea
method will do what you're looking to accomplish:
Console.BufferWidth = Console.WindowWidth;
Console.BufferHeight = Console.WindowHeight;
string s = "";
for (int i = 0; i < Console.BufferWidth; i++)
s += (i % 10).ToString();
Console.Write(s);
//
// copy the buffer from its original position (0, 0) to (0, 24). MoveBufferArea
// does NOT reposition the cursor, which will prevent the cursor from wrapping
// to a new line when the buffer's width is filled.
Console.MoveBufferArea(0, 0, Console.BufferWidth, Console.BufferHeight, 0, 24);
Console.ReadKey();
Here's the result:

回答3:
Set the BufferHeight and BufferWidth after you've written the string.
Console.CursorTop = Console.WindowHeight - 1;
Console.SetCursorPosition(0, Console.CursorTop);
string s = "";
for (int i = 0; i < Console.BufferWidth; i++)
s += (i % 10).ToString();
Console.Write(s);
Console.CursorTop = 0;
Console.BufferWidth = Console.WindowWidth;
Console.BufferHeight = Console.WindowHeight;
Console.ReadKey();
来源:https://stackoverflow.com/questions/25084384/filling-last-line-in-console