相对于文本的最后一行设置光标位置C#控制台应用程序

时间:2018-08-17 10:01:39

标签: c# console-application

美好的一天

如果这是控制台的输出:

.
.
.
.
Hello World!

我想设置光标的位置,例如距文本的最后一行20行。如果最后一行明显在不断变化,我该怎么办?

谢谢您的时间。

2 个答案:

答案 0 :(得分:1)

Console.SetCursorPosition(Console.CursorLeft, (Console.CursorTop+20))

如果对您很重要,则通过CursorLeft可以将其保持在相同的左侧位置。否则,您只能传递0。

Console.SetCursorPosition(0, (Console.CursorTop+20))

答案 1 :(得分:1)

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace CUrsorPosition
{
    class Program
    {
       static int lastCursorLocation = 0;
       //customCursorPosition say which line number you want the cursor to //set after the last text for example i have set it to 1 so next line to hellow //world
       static int customCursorPosition = 1;
        static void Main(string[] args)
        {
            // int customCursorPosition = 0;
            WriteLine(".");
            WriteLine(".");
            WriteLine(".");
            WriteLine(".");

            int x = Console.CursorLeft;
            int y = Console.CursorTop;
            Console.CursorTop = Console.WindowTop + Console.WindowHeight - 1;
            Console.SetCursorPosition(x, y);
            WriteLine("Hello World");
            Console.SetCursorPosition(0, y+ customCursorPosition);
            Console.ReadLine();


        }
        static void WriteLine(string message, [CallerLineNumber] int lineNumber = 0)
        {
            Console.WriteLine(lineNumber + ": " + message);
        }
        static void WriteLine(string message)
        {
            StackFrame callStack = new StackFrame(1, true);
            var lineNumber = callStack.GetFileLineNumber();
            lastCursorLocation = callStack.GetFileLineNumber();
            Console.WriteLine(message);

        }
    }
}