将控制台中的输入光标移到下一行

本文关键字:一行 控制台 输入 光标 | 更新日期: 2023-09-27 18:25:07

这是一个有两个线程的程序;一个用于输出,一个用于输入。(其中_是控制台光标)

Please enter a number:
12_

当您键入12时,会生成清除当前行并在其上写入的输出,因此会发生这种情况:

Please enter a number:
Output
_

我如何才能把你仍在输入的12移到下一行,这样你就不必重新输入了?

提前谢谢。

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {
            Program prog = new Program();
            Thread t1 = new Thread(prog.getInput);
            t1.Start();
            prog.otherThread();
        }
        public void otherThread()
        {
            while (true)
            {
                System.Threading.Thread.Sleep(3000);
                ClearCurrentConsoleLine();
                Console.WriteLine("Output");
            }
        }
        public void getInput()
        {
            while (true)
            {
                string msg;
                msg = Console.ReadLine();
            }
        }
        public static void ClearCurrentConsoleLine()
        {
            int currentLineCursor = Console.CursorTop;
            Console.SetCursorPosition(0, Console.CursorTop);
            for (int i = 0; i < Console.WindowWidth; i++)
            {
                Console.Write(" ");
            }
            Console.SetCursorPosition(0, currentLineCursor);
        }
    }

正如你所看到的,当你输入"你好"answers"不要输入"时,3秒钟后它将被"输出"覆盖。我想在被覆盖之前将"Hello"和输入移到第二行。

将控制台中的输入光标移到下一行

我刚刚发现了这篇文章(web归档),其中讨论了光标的位置和修改。我发现它很直接。

它的中心是:

      int left = Console.CursorLeft;
      int top = Console.CursorTop;
      Console.SetCursorPosition(15, 20);

如果我理解正确,这应该会起作用。

  1. 将字符串msg设为全局。在所有函数之外声明它
  2. 现在只需在清除上一行后将其打印到下一行即可。。

    班级计划{
    字符串消息;

    static void Main(string[] args)
    {
        Program prog = new Program();
        Thread t1 = new Thread(prog.getInput);
        t1.Start();
        prog.otherThread();
    }
    public void otherThread()
    {
        while (true)
        {
            System.Threading.Thread.Sleep(3000);
            ClearCurrentConsoleLine();
            Console.WriteLine("Output");
        }
    }
    public void getInput()
    {
        while (true)
        {
            msg = Console.ReadLine();
        }
    }
    public static void ClearCurrentConsoleLine()
    {
        int currentLineCursor = Console.CursorTop;
        Console.SetCursorPosition(0, Console.CursorTop);
        for (int i = 0; i < Console.WindowWidth; i++)
        {
            Console.Write(" ");
        }
        Console.SetCursorPosition( 0, currentLineCursor + 1 );
        Console.Write(msg);
        Console.SetCursorPosition(0, currentLineCursor);
    }
    

    }