Search code examples
c#user-interfaceconsoleselectionhighlight

How to Highlight and select Console Text in C# console


I wish to create an old style terminal emulation, creating commands seems to be easy, but I want to give the user a very vintage UI interface.
I want to be able to print text to the console, Ex: "Logs" and then when the user presses an arrow key, I want it to be highlighted and once it is selected I would like to be able to hit enter and execute the selected command.
I am using Visual Studio Express 2012 for Desktop btw.


Solution

  • I think you will have to rewrite the lines you already put on the screen to change their color and background as a reponse to arrow inputs

    I think you will be able to use

    Console.SetCursorPosition
    

    to put your cursor back on the line you want to change color and then

    Console.BackgroundColor
    Console.ForegroundColor
    Console.ResetColor()
    

    to modify the colors of what you are writing

    So basically you need to

    • clear the screen when you start up to know the positions of each option
    • respond to magic keypresses
    • rewrite the color/background of the item your magic keypress highlights

    Remember to set the cursor back to its original position after you rewrite the highlighted part. This is a crude sample to show what I mean.

    Console.Clear();
    Console.WriteLine("Option 1");
    Console.WriteLine("Option 2");
    Console.WriteLine("Option 3");
    Console.WriteLine();
    Console.Write("input: ");
    
    var originalpos = Console.CursorTop;
    
    var k = Console.ReadKey();
    var i = 2;
    
    while (k.KeyChar != 'q')
    {
    
        if (k.Key == ConsoleKey.UpArrow)
        {
    
             Console.SetCursorPosition(0, Console.CursorTop - i);
             Console.ForegroundColor = ConsoleColor.Black;
             Console.BackgroundColor = ConsoleColor.White;
             Console.WriteLine("Option " + (Console.CursorTop + 1));
             Console.ResetColor();
             i++;
    
        }
    
        Console.SetCursorPosition(8, originalpos);
        k = Console.ReadKey();
    }
    

    I think it might be easier to create a routine that prints all the necessary text on-screen and rewrite the entire text each time the user presses a magic key, highlighting as you go.