2017-08-19 54 views
1

我正在嘗試創建一個控制檯應用程序,該控制檯應用程序在給出輸入的能力的角落給了我一個更新時鐘。更新時鐘,同時能夠輸入C#控制檯

我試過使用多個線程,但它給了我怪異的錯誤。

我的時鐘功能:

public class Work 
{ 
    public void Count() 
    { 
     for (int i = 0; i < 100; i++) 
     { 
      DateTime date = DateTime.Now; 
      Console.SetCursorPosition(0, 1); 
      Console.Write(new string(' ', Console.WindowWidth)); 


      Console.SetCursorPosition((Console.WindowWidth - 8)/2, 0); 
      Console.Write(String.Format("{0:HH:mm:ss}", date)); 
      Console.WriteLine(); 
      if (i == 90) 
      { 
       i = 0; 
      } 
      else 
      { 
       // Continue 
      } 
     } 
    } 
} 

我的主要功能:

class Program 
{ 
    public static void Main(string[] args) 
    { 
     Console.CursorVisible = false; 
     Work w = new Work(); 
     Console.WriteLine("Main Thread Start"); 

     ThreadStart s = w.Count; 
     Thread thread1 = new Thread(s); 
     thread1.Start(); 
     int i = 2; 
     Console.SetCursorPosition(0, i); 
     i = i + 1; 
     Console.WriteLine("Input:"); 
     string input = Console.ReadLine(); 
     Console.WriteLine(input); 
    } 

} 

有誰知道我能做到這一點,是沒有辦法,我可以寫一個時鐘以不同的任何可能的方式光標或者其他的東西?

回答

0

試着改變你的代碼,這樣

class Program 
{ 
    static void Main(string[] args) 
    { 
     Console.CursorVisible = false; 
     var w = new Work(); 
     Console.WriteLine("Main Thread Start"); 

     ThreadStart s = w.Count; 
     var thread1 = new Thread(s); 
     thread1.Start(); 
     int i = 2; 
     Console.SetCursorPosition(0, i); 
     var format = "Input:"; 
     Console.WriteLine(format); 
     Console.SetCursorPosition(format.Length + 1, i); 
     string input = Console.ReadLine(); 
     Console.WriteLine(input); 
    } 
} 

public class Work 
{ 
    public void Count() 
    { 
     while (true) 
     { 
      Thread.Sleep(1000); 
      var originalX = Console.CursorLeft; 
      var originalY = Console.CursorTop; 

      Console.SetCursorPosition(0, 1); 
      Console.Write(new string(' ', Console.WindowWidth)); 

      Console.SetCursorPosition((Console.WindowWidth - 8)/2, 0); 
      Console.Write("{0:HH:mm:ss}", DateTime.Now); 

      Console.SetCursorPosition(originalX, originalY); 
     } 
    } 
} 

主要的想法是存儲原來的光標位置繪製你的時鐘之前,然後renurn回來。

var originalX = Console.CursorLeft; 
var originalY = Console.CursorTop; 

Console.SetCursorPosition(originalX, originalY);