Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display string value real time

I'm writing a console program, and my code looks like this:

Configuration.cs

public static class Configuration
{
    public static string Message = "";
}

Menu.cs

class Menu
{
    public static void showMenu()
    {
        Console.Clear();
        Console.WriteLine("1: SOMETHING");
        Console.WriteLine("2: SOMETHING");
        Console.WriteLine("3: SOMETHING");
        Console.WriteLine("SYSTEM MSG: " + Configuration.Message);
        Console.Write("INPUT: ");
    }
}

Program.cs

...
static void Main(string[] args)
{
    ...
    int choice;

    while(true)
    {
        Menu.showMenu();
        choice = Convert.ToInt32(Console.ReadLine());

        switch(choice)
        {
            case 1:
            Configuration.Message = "HELLO!";
            break;

            case 2:
            Configuration.Message = "HI!";
            break;

            case 3:
            Configuration.Message = "WHAT?!";
            break;
        }
    }
}
...

For now, when I change Configuration.Message, it will display on the menu because the showMenu method clears the console and show the string again.

But what I want to make is without Clear method, I want to show Configuration.Message for real time. I was thinking that using Timer and refresh the menu every second, but it is not efficient (feels like cheating). How can I do this?

like image 271
KimchiMan Avatar asked Sep 14 '26 01:09

KimchiMan


1 Answers

When you write to the Console, the write operation begins at the current cursor position. So...

Look at the properties and methods of the System.Console class, in particular:

  • CursorLeft gets or sets the column position of the cursor
  • CursorTop gets or sets the row position of the cursor
  • SetCursorPosition( int left , int top ) sets both row and column position.

As each character is written, the cursor moves one position to the right, wrapping to the next row when the cursor would move past the BufferWidth column (e.g. if you're console's buffer is 80 columns wide, writing the 80th column would advance the column outside the buffer (column 81), so the cursor would move to column 1 of the next row.

For what you want to do, you could also look at P/Invoking the native Win32 cursor methods, or use something like one of the .Net derivations of *nix's curses(3) and Gnu's ncurses(3):

  • Mono-Curses: http://www.mono-project.com/MonoCurses
  • Curses Sharp: http://curses-sharp.sourceforge.net/
  • Curses X: http://www.csharpcity.com/2013/consolecurses-library-for-c/
like image 168
Nicholas Carey Avatar answered Sep 16 '26 16:09

Nicholas Carey