1

I'm trying to create a console application that gives me an updating clock in the corner with the ability to give an input.

I've tried using multiple threads but it gives me weird errors.

My clock function:

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
            }
        }
    }
}

My main function:

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);
    }

}

Does anybody know how I can achieve this, is there any possible way that I can write to a clock with a different cursor or something along the lines of that?

1 Answers1

0

Try change your code like this

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);
        }
    }
}

The main idea is to store original cursor position before drawing your clock and then renurn it back.

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

Console.SetCursorPosition(originalX, originalY);
Mitya
  • 632
  • 5
  • 18