My program can be run with the GUI or from the command line. When it is run from the command line, I ask for more commands once the program has started (using Console.Readline()). However, it will not accept any input from the user until they press Enter (BEFORE they type their input).
I start the project as a console project as so:
[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 outputs the below when the user enters "/Exit" (for example):
Enter additional commands: /Exit
'/Exit' is not recognized as an internal or external command, operable program or batch file.
However, if the user first presses Enter (right after "Enter additional commands: "), they can enter commands for the program fine.
Any idea on why they must press enter first? It is not intuitive for the user to press it before they type, so I would like to change it.
Thank you!
The problem is that you attached to the console of the command line processor, cmd.exe. Now there are two programs that are interested in input. Cmd.exe wins, it doesn't know what the /Exit command is supposed to mean. And displays the error message you saw. No problem when you press Enter first, cmd.exe doesn't mind that. And your program gets a turn.
Create your own console, always call AllocConsole().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With