Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Edit text in C# console application? [duplicate]

Is there a way to edit text in a C# console application? In other words, is it possible to place pre-defined text on the command line so that the user can modify the text and then re-submit it to the app?

like image 228
Chev Avatar asked Sep 27 '11 07:09

Chev


People also ask

What is editing in C programming?

Edit: Use an editor to develop the code in your programming language of choice. Result: a text file with the source code of the program (e.g. hello. c) Compile: Use a compiler to translate the source code into a version understood by the machine.

Which command is used to edit text files?

The MS-DOS text editor, edit, lets you view, create, or modify any text file on your computer. While running edit, a screen similar to the picture below is shown.


2 Answers

Yes. You need to use method SetCursorPosition of Console. Example:

    Console.WriteLine("hello");
    Console.SetCursorPosition(4, 0);
    Console.WriteLine("      ");

It will display 'hell' You need custom realization of ReadLine method which let you to edit n-symbols (default string) in Console and return string from a user. This is my example:

static string ReadLine(string Default)
{
    int pos = Console.CursorLeft;
    Console.Write(Default);
    ConsoleKeyInfo info;
    List<char> chars = new List<char> ();
    if (string.IsNullOrEmpty(Default) == false) {
        chars.AddRange(Default.ToCharArray());
    }

    while (true)
    {
        info = Console.ReadKey(true);
        if (info.Key == ConsoleKey.Backspace && Console.CursorLeft > pos)
        {
            chars.RemoveAt(chars.Count - 1);
            Console.CursorLeft -= 1;
            Console.Write(' ');
            Console.CursorLeft -= 1;

        }
        else if (info.Key == ConsoleKey.Enter) { Console.Write(Environment.NewLine); break; }
        //Here you need create own checking of symbols
        else if (char.IsLetterOrDigit(info.KeyChar))
        {
            Console.Write(info.KeyChar);
            chars.Add(info.KeyChar);
        }
    }
    return new string(chars.ToArray ());
}

This method will display string Default. Hope I understood your problem right (I doubt in it)

like image 148
Vasya Avatar answered Oct 02 '22 20:10

Vasya


One thing that came to my mind is to...simulate keystrokes. And a simple example using SendKeys:

static void Main(string[] args)
{
    Console.Write("Your editable text:");
    SendKeys.SendWait("hello"); //hello text will be editable :)
    Console.ReadLine();
}

NOTE: This works only on active window.

like image 38
Renatas M. Avatar answered Oct 02 '22 18:10

Renatas M.