我正在尝试创建一个控制台应用程序,它在角落里为我提供了一个能够提供输入的更新时钟。
我尝试过使用多个线程,但它给我带来了奇怪的错误。
我的时钟功能:
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 :(得分: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);
}
}
}
主要思想是在绘制时钟之前存储原始光标位置,然后将其重新标记。
var originalX = Console.CursorLeft;
var originalY = Console.CursorTop;
Console.SetCursorPosition(originalX, originalY);