简体   繁体   English

如何在C#控制台应用程序的行首处允许用户输入?

[英]How can I allow user input from the beginning of the line in C# console app?

I know I can use Console.ReadLine() to allow user input but it only allows user input from where the cursor is positioned, I want a way to be able to allow user input from the beginning of the line (over the whole line) and not only from where the cursor is positioned. 我知道我可以使用Console.ReadLine()来允许用户输入,但是它只允许从光标所在的位置进行用户输入,我希望有一种方法可以允许用户从行的开头(整行)而不仅仅是从光标所在的位置开始。 for example: 例如:

for (int i = 1;i <= 5;i++) Console.Write(i+" ");
string x = Console.ReadLine();

This would give the following output: 这将给出以下输出:

1 2 3 4 5 _

Where '_' refers to the cursor, this way, the user will be able to write only from the cursor position - he cannot use backspace to delete the former characters too. 在“ _”指的是光标的情况下,这样,用户将只能从光标位置进行写操作-他也不能使用退格键删除以前的字符。 So how can I allow user input over the whole line while the cursor is not at the beginning of the line? 因此,当光标不在行首时,如何允许用户在整行上输入?

This is ready to go example with custom input handling. 这是准备使用自定义输入处理的示例。 Of cource this is require some tweaks towards performance but it should give you and idea where to begin. 当然,这需要对性能进行一些调整,但是它应该使您和从哪里开始有了想法。

    static void Main(string[] args)
    {
        List<char> outputString = new List<char>();
        outputString = "test".ToCharArray().ToList();
        //If there is something in outputString write it to buffer and set cursor position
        if (outputString.Count > 0)
        {
            Console.Write(outputString.Select(x => x.ToString()).Aggregate((x, y) => x + y));
        }

        while (true)
        {
            //This will read user input but it will not print it to the console window 
            var key = Console.ReadKey(true);
            //Allow user maniputate cursor to the right
            //Here you can add another condition to prevent line overflow or some constrains
            //if(Console.CursorLeft < 30)
            if (key.Key == ConsoleKey.RightArrow && Console.CursorLeft < outputString.Count)
            {
                Console.SetCursorPosition(Console.CursorLeft + 1, Console.CursorTop);
            }
            else if (key.Key == ConsoleKey.LeftArrow && Console.CursorLeft > 0)
            {
                Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
            }
            //Here you should add all keys that your input should take, special characters are ok above ASCII number 32 which is space
            else if (key.KeyChar >= 48 && key.KeyChar <= 57 || //Read numbers
                key.KeyChar >= 64 && key.KeyChar <= 90 || //Read capital letters
                key.KeyChar >= 97 && key.KeyChar <= 122 || //Read lower letters
                key.Key == ConsoleKey.Spacebar)
            {
                Console.Write(key.KeyChar);
                if(Console.CursorLeft > outputString.Count)
                {
                    outputString.Add(' ');
                }
                outputString[Console.CursorLeft - 1] = key.KeyChar;
            }
            //This will remove character
            else if (key.Key == ConsoleKey.Backspace && Console.CursorLeft > 1)
            {
                ClearCurrentConsoleLine();
                outputString.RemoveAt(Console.CursorLeft - 1);
                var currentLeft = Console.CursorLeft;
                Console.CursorLeft = 0;
                Console.Write(outputString.Select(x => x.ToString()).Aggregate((x,y) => x + y));
                Console.CursorLeft = currentLeft - 1;
            }
            //This ends input loop
            //You can add more keys to break current loop with OR condition
            else if (key.Key == ConsoleKey.Enter)
            {
                break;
            }
        }
        //Display result and wait for any key
        Console.WriteLine(outputString.Select(x => x.ToString()).Aggregate((x, y) => x + y));
        Console.ReadKey();
    }

    //Clears current console line and sets cursor at where it was before
    public static void ClearCurrentConsoleLine()
    {
        int currentLineCursorTop = Console.CursorTop;
        int currentLineCursorLeft = Console.CursorLeft;
        Console.SetCursorPosition(0, Console.CursorTop);
        Console.Write(new string(' ', Console.WindowWidth));
        Console.SetCursorPosition(currentLineCursorLeft, currentLineCursorTop);
    }

You could use Console.CursorLeft = 0; 您可以使用Console.CursorLeft = 0; for this. 为了这。 The advantage in comparison to Console.SetCursorPosition is, that you don't have to evaluate the y-coordinate, so that the cursor stays in the current line. Console.SetCursorPosition相比,优点是您不必评估y坐标,因此光标停留在当前行。

I want to make an example for this (in both cases we want the cursor to go to the beginning of the line): 我想为此做一个例子(在两种情况下,我们都希望光标移至行首):

Console.SetCursorPosition(0, Console.CursorTop); //With SetCursorPosition
Console.CursorLeft = 0; //With CursorLeft

However, I don't think there's an elegant way of letting the user delete the chars written by the program. 但是,我认为没有一种让用户删除程序编写的字符的优雅方法。 You could still constantly check wether the user presses Backshift and then delete the last character and move the cursor back, while you'd have to check that asynchronously what wouldn't result in a nice solution. 您仍然可以不断检查用户是否按下Backshift键,然后删除最后一个字符并向后移动光标,同时您必须异步检查不会导致什么好的解决方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在不中断用户输入的情况下在C#Windows控制台应用程序中更新行? - How can I update a line in a C# Windows Console App while without disrupting user input? 如何在 Mac 控制台应用程序 C# 上禁用用户输入? - How can I disable user input on mac console app C#? C#控制台:如何从命令行读取管道输入 - c# console: how can i read piped input from the command line 如何允许用户随时通过输入退出控制台 C# - How to allow a user to exit from the Console at any time C# with an input 如何从 c# 控制台应用程序中的用户输入创建多个 object? - How to create more than one object from user input in c# console app? 如何更新 C# Windows 控制台应用程序中的当前行? - How can I update the current line in a C# Windows Console App? 如何在C#中轻松地从控制台或文件中的用户获取输入? - How to take the input from user in console or file with ease in c#? 如何根据asp.net C#下拉菜单中的用户输入在图表上添加一条直线 - How can I add a straight line on my chart on the basis of user input from drop down menu in asp.net c# C#控制台应用程序:在用户输入有效数据之前,如何继续返回错误消息? - C# console app: How can I continue returning an error message until user enters valid data? 如果用户在我的 C# 程序中打印“x”,我如何让控制台应用程序退出? - How can i make the console app Exit if the user prints 'x' in my C# program?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM