I'm creating a c# winforms project that can be run as a GUI or can be operated from the command line. Currently, I can process command line input and arguments. I can run the program from command line and I can use the program to process the arguments. But Console.Writeline() does absolutely nothing. Any clue why that could be?
It has to do with the project type as you configure it on App tab on the properties of the project, you have 3 options:
- Console Application
- Win Application
- Class Library
If you work with Win Application, however, you can also process the command line arguments, because these are received on the Main function.
The project must be set to compile to a console application for console function to work. On the other hand, it will then always have a console window, even when run as GUI. I do not know of a workaround for this (but would be interested to hear of it if there is one).
This is because you have written a winforms app - this means that System.Console.Out
(i.e. the standard output stream) is set to Stream.Null
. This means that any calls to that stream will silently fail.
You are able to process input from the command line because they come from a different stream. The moral of the story is that you can have a winforms app, or a command line app, but not both at once.
For the most part, see the answer here. However, I would like to point out the existence of the FreeConsole()
API call, which allows you to gracefully close the console.
[DllImport("kernel32.dll")]
static extern int FreeConsole()
One thing I'd like to note: you may see some weirdness of a command prompt appearing in front of your console output, if you're launching from an existing console and attaching to that with AttachConsole
(as opposed to AllocConsole
).
This is a timing issue which is hard to work around. If that's a problem, set your application to be a Console application like the others suggested. It will have the effect of no command prompt appearing until the application closes however, which might not be what you want if you're opening a winform.
In response to your comment: it's either AttachConsole
or AllocConsole
. The example I linked tries to attach to an existing console first. If that fails (most likely because it doesn't exist), it creates a new console window instead.
If you find a way to have the best of both worlds in terms of command-line behavior and GUI interactive mode, please let me know. I haven't done any in-depth searching for a solution, but I have a few minor apps that would benefit.
By the way: if you plan on using pipes on your command line (redirecting output to a file for example), that won't work like this unfortunately.