After printing few lines on console window, how to get bach to the first line to print new data

泪湿孤枕 提交于 2019-12-14 03:10:51

问题


After printing some data(a, b, c)

a

b

c

on console screen, how to get back to the first line and print x, y, z like this

a x

b y

c z


回答1:


You will have to use explicit cursor positioning for this to work on the console, it could be something like this:

public class SomeCharPos{
   private char ch;
   private int row, col;
   public SomeCharPos(char ch, int row, int col){
      this.ch = ch;
      this.row = row;
      this.col = col;
   }
   public char SomeChar{
      get{ return this.ch; }
   }
   public int Row{
      get{ return this.row; }
   }
   public int Col{
      get{ return this.col; }
   }
}

public class DemoIt{
   public Dictionary thisDict = new Dictionary();
   public DemoIt(){
       thisDict.Add('a', new SomeCharPos('a', 1, 1));
       thisDict.Add('b', new SomeCharPos('a', 2, 1));
       thisDict.Add('c', new SomeCharPos('a', 3, 1));
          ....
       thisDict.Add('x', new SomeCharPos('x', 1, 3));
       thisDict.Add('y', new SomeCharPos('x', 2, 3));
       thisDict.Add('z', new SomeCharPos('x', 3, 3));
   }
   public void DrawIt(){
       foreach (SomeCharPos pos in thisDict.Values){
          Console.SetCursorPosition(pos.Col, pos.Row);
          Console.Write(pos.SomeChar);
       }
   }
}

Hope this helps, Best regards, Tom.




回答2:


static void Main(string[] args)
{
    Random rand = new Random();
    int maxShoots = 100;

    Console.Clear();
    for (int loop = 0; loop < maxShoots; loop++)
    {
        Console.CursorLeft = rand.Next(Console.WindowWidth);
        Console.CursorTop = rand.Next(Console.WindowHeight);
        Console.Write("x");

        Console.CursorLeft = 0;
        Console.CursorTop = 0;
        Console.Write("Iteration " + loop);

        Thread.Sleep(rand.Next(100));
    }

    Console.CursorLeft = 0;
    Console.CursorTop = Console.WindowHeight-1;
    Console.ReadKey();
}



回答3:


You can control the cursor through Console.CursorTop, Console.CursorLeft properties.



来源:https://stackoverflow.com/questions/2325832/after-printing-few-lines-on-console-window-how-to-get-bach-to-the-first-line-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!