2013-10-09 34 views
-1

我正在研究c#控制檯應用程序。在屏幕上顯示計時器並同時要求用戶輸入?

我必須在指定的光標位置在屏幕上顯示一個計時器,同時用戶應該輸入一些東西。

我該怎麼做?

Console.SetCursorPosition(x, y); 
//timer code here 
Console.SetCursorPosition(x, y); // cursor goes to some other location because timer is displayed at top-right of the screen. 

我的問題是,這種方法是不同步的。 我必須等到光標移動到該位置,然後顯示時間並返回,以便我可以輸入。

enter image description here

+0

你說你正在開發一個控制檯應用程序,但是你用[tag:ASP.NET]標記了它。說明? – JDB

+0

'我的問題是這種方法不同步'你是什麼意思? – tnw

+0

你可以發佈一些更多的代碼?例如,用戶輸入的地方。同時發佈x和y的實際值也會有所幫助。 – bytefire

回答

0

即使在讀取線可以使用Timer。請參見下面的代碼的工作示例:

class Program 
{ 
    private static System.Timers.Timer _timer; 

    static void Main(string[] args) 
    { 

     _timer = new System.Timers.Timer(1000); 
     _timer.Elapsed += Timer_Elapsed; 
     _timer.AutoReset = true; 
     _timer.Start(); 

     Console.CursorLeft = 0; 
     Console.CursorTop = 5; 
     // Type something here... 
     var l_readline = Console.ReadLine(); 
     // Print it out... (to show it correctly reads the input) 
     Console.WriteLine(l_readline); 
     Console.ReadKey(true); 
    } 

    private static void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) 
    { 
     int l_left = Console.CursorLeft; 
     int l_top = Console.CursorTop; 

     Console.CursorLeft = 0; 
     Console.CursorTop = 0; 
     Console.Write(DateTime.Now.ToLongTimeString()); 
     Console.CursorLeft = l_left; 
     Console.CursorTop = l_top; 
    } 

} 

只要你重新設置光標位置返回到它的您完成後原來的位置,我不認爲你會與大多數形式的輸入比較麻煩。

+0

你的頭像從哪裏來?看起來像一個整潔的節目。 :) – jp2code

+0

這是來自Dr. Who的[Cyber​​man](https://www.google.com/search?q=cyberman&es_sm=122&source=lnms&tbm=isch&sa=X&ei=P6hVUvqNKu66yAHN1ICQDw&ved=0CAkQ_AUoQQ&biw=1440&bih=775&dpr=1)! –

+0

謝謝你,親切的先生。 希望我能代表你,但不能。 –

0

來處理這樣的事情是將時間存儲當前光標(X,Y),寫信給你的時間最簡單的方法(X,Y),然後將光標移回光標( X,Y)

private const int TIME_LEFT = 40; 
private const int TIME_RIGHT = 2; 

private void WriteTime() { 
    var left = Console.CursorLeft; 
    var right = Console.CursorTop; 
    try { 
    Console.SetCursorPosition(TIME_LEFT, TIME_RIGHT); 
    Console.Write(DateTime.Now); 
    } finally { 
    Console.SetCursorPosition(left, right); 
    } 
} 

不知道你在做什麼,這是我最適合你的建議。

這應該比人類可以做出的反應更快。

相關問題