简体   繁体   English

将文本写出到控制台输出作为输入

[英]Write out text to the console output as an input

I'm writing a console application with C# and there is a question at the beginning of the program: 我正在用C#编写控制台应用程序,程序开头有一个问题:

Console.WriteLine("Would you like to create the config folder? (y/n)");

I would like to set a default "y" after this line, so it's enough to the user just to press the Enter. 我想在此行之后设置默认的“ y”,因此对于用户来说只需按Enter键就足够了。 (or delete it with backspace if (s)he wants "n") (如果需要“ n”,则使用退格键将其删除)

Is this even possible? 这有可能吗? How? 怎么样?

Just use 只需使用

Console.WriteLine("");
Console.Write("y")

so Y is on the next line and they just have to press enter. 所以Y在下一行,他们只需要按Enter。

That behavior is a bit strange, in my opinion. 我认为这种行为有点奇怪。 What I would do is this: 我要做的是:

Console.WriteLine("Would you like to create the config folder? (Y/N) [Y]");

ConsoleKey optionKey;
do
{
    ConsoleKeyInfo key = Console.ReadKey(true);
    optionKey = key.Key == ConsoleKey.Enter ? ConsoleKey.Y : key.Key;
} while (optionKey != ConsoleKey.Y && optionKey != ConsoleKey.N);

Console.WriteLine(optionKey);

if (optionKey != ConsoleKey.N)
{
    // Do your stuff
}

The correct behavior here should be show something like 这里的正确行为应显示为

Console.WriteLine("Would you like to create the config folder? (y/n) [y]");

This tells the user that y is the default and by just pressing enter it would be auto selected. 这告诉用户y是默认值,只需按Enter即可自动选择。 I think this would be faster in case a user want to select n because then the user don't have to delete y and then enter his/ choice. 我认为这在用户想要选择n情况下会更快,因为那样的话,用户不必删除y并输入他的选择。

Consider if the user has to go through multiple question and have to select n for all of them. 考虑用户是否必须经历多个问题并为所有问题都选择n It would be a little annoying. 有点烦人。

Simple way to code (just a pseudo-code) it is: 编写(只是伪代码)的简单方法是:

boolean selection = true; //false if 'n' is default
if(userinput == 'n') selection = false;

If you still want to write a changeable output use: 如果您仍然想编写可变的输出,请使用:

Console.WriteLine("Would you like to create the config folder? (y/n)");
SendKeys.SendWait("y");
Console.ReadLine();

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM