如何在倒数时间运行时将光标设置为输入值?

时间:2015-12-30 09:38:27

标签: c# multithreading console

我使用了两个同时运行的线程,一个线程用于显示timeleft(倒计时从3s到0s),另一个线程用于从用户获取输入并检查输入。 / p>

这里的问题是:如何将cursor设置为保留在一个位置以获取用户输入值,而Timeleft仍然会在Console window中每秒显示一次。 (每次显示Timeleft光标移动到另一个地方,我无法输入值。)

Random rd = new Random();
        int totalscore = 0;

        for (int i = 1; i <= 10; i++)
        {
            int num1 = rd.Next(50);
            int num2 = rd.Next(50);
            int sum = num1 + num2;
            int input;

            Console.SetCursorPosition(0,0);
            Console.Write("Question {0}", i);

            Console.SetCursorPosition(0,1);
            Console.Write("{0} + {1}", num1, num2);

            Console.SetCursorPosition(0, 3);
            Console.Write("Total Score : {0}", totalscore);

            Thread t1 = new Thread(() =>
            {
                for (int t = 3; t > 0; t--)
                {
                    Console.SetCursorPosition(0, 2);
                    Console.Write("timeleft : {0}", t);
                    Thread.Sleep(1000);
                }
            });
            t1.Start();

            Thread t2 = new Thread(() =>
            {
                while (true)
                {
                    Console.SetCursorPosition(10, 1);
                    input = Convert.ToInt32(Console.ReadLine());
                    if (input == sum)
                    {
                        totalscore += 10;
                        t1.Abort();
                        break;
                    }
                    else
                    {
                        t1.Abort();
                        break;
                    }
                }
            });
            t2.Start();

            Console.SetCursorPosition(0, 3);
            Console.WriteLine("Total score : {0}", totalscore);

            while (true)
            {
                if (t1.IsAlive == false)
                {
                    t2.Abort();
                    break;
                }
            }

            Console.Clear();
        }

1 个答案:

答案 0 :(得分:0)

设置input

后,您需要将光标设置回timeleft位置
for (int t = 3; t > 0; t--)
{
    Console.SetCursorPosition(0, 2);    //for timer
    Console.Write("timeleft : {0}", t);
    Console.SetCursorPosition(10, 1);   //resetting for total score
    Thread.Sleep(1000);
}