在控制台中填写最后一行

时间:2014-08-01 16:08:52

标签: c# console

我想填写/更新控制台的整个底线。例如:

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();
}

问题在于,当打印文本时,它会移动到新行。类似的问题表明将光标移动到0,0,但是只有当缓冲区大小大于窗口大小时才能使用,我希望缓冲区宽度和窗口宽度相等(去除滚动条)。 有任何想法吗?我能得到的最接近的是打印到更高的线并将其移动到最后一行,但是在整个项目中这是不可接受的。

编辑: 问题的最后一句是专门讨论movebufferarea。这个例子可以看出这不起作用的原因:

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);
    }
}

句子会频繁闪烁,因为它先打印然后移动。

3 个答案:

答案 0 :(得分:2)

由于光标总是在您编写的文本之后尾随,您可以编写少一个字符以避免转到下一行,或者只是将字符直接写入缓冲区(我相信,Console.MoveBufferArea可以用于那个)。

答案 1 :(得分:1)

正如乔伊所说,使用MoveBufferArea方法可以完成你想要完成的任务:

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();

结果如下:

enter image description here

答案 2 :(得分:0)

在你写完字符串后设置BufferHeight和BufferWidth。

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();
相关问题