C #: Why should the user press Enter before Console.Readline () starts reading?

My program can be launched using the graphical interface or from the command line. When it starts from the command line, I request more commands after starting the program (using Console.Readline ()). However, it will not accept any data from the user until they press Enter (BEFORE they enter their input).

I run the project as a console project like this:

[DllImport("kernel32.dll")] private static extern bool AllocConsole(); [DllImport("kernel32.dll")] private static extern bool AttachConsole(int pid); private static void Main(string[] args) { if (args.Length > 0 && args[0] == "noGUI") { if (!AttachConsole(-1)) { AllocConsole(); } ... List<string> newInput; do { Console.WriteLine(); Console.Write(@"Enter additional commands: "); string inputStr = Console.ReadLine(); newInput = GetArgs(inputStr); if (newInput.Count == 0) { Console.WriteLine(); Console.WriteLine(@"Please enter a valid command"); continue; } ... } while(true) } ... 

Which displays below when the user enters "/ Exit" (for example):

Enter additional commands: / Exit

'/ Exit' is not recognized as an internal or external command that runs a program or batch file.

However, if the user first presses Enter (immediately after "Entering additional commands:"), they can enter the commands for the program in order.

Any idea on why they should click first? It is not interesting for the user to click on it before they print, so I would like to change it.

Thanks!

+8
c # console-application
source share
2 answers

The problem is that you are connected to the cmd.exe command line processor console. Now there are two programs that are interested in entering. Cmd.exe wins; it does not know what the / Exit command means. And displays the error message you saw. No problem the first time you press Enter, cmd.exe does not mind. And your program gets a twist.

Create your own console, always call AllocConsole ().

+14
source share

Because [Enter] means end of line!

If you don't like this, just use Console.ReadKey() or Console.Read() .

0
source share

All Articles