Re: Console Output from a Winforms Application
This is a reply from C#411. Tim shows how to AttachConsole for a WinForms Application. One problem is that the standard output and error output are not correctly handled so they can't be redirected. The comments has some useful hint about this.
After reading it and testing in Visual Studio (2008), here is my initial solution:
Right click the project and select "Property", in the Application tab, you can see "Output Type:" is "Windows Application" in default for Form application. Change it to Console Application, there is no modification needed in your source code. All problem solved. The output can be redirected to text file, and the command prompt is not messed up.
After doing so, there are always 2 windows, 1 for console and 1 for WinForm. What I really want is:
If the application is started with parameters, then start console window (only)
If the application is started without parameter, such as clicking the icon from Explorer, then start the WinForm.
I found FreeConsole WinAPI from Tim's solution, so my final solution is , in addition to the initial solution:
1. In Program.cs, separate the 2 cases, has parameter or not:
[DllImport("kernel32.dll")]static extern bool FreeConsole();
static void Main(string args)
if (args.Length != 0)
2, In the Form1, add a new construction function to deal with parameters:
Boolean CloseAfterCommandLine;3, Modify the original Form1(void) to have CloseAfterCommandLine = false;
public Form1(string commands)
Work with the parameters
CloseAfterCommandLine = true;
4, In Form1.Load, close the WinForm if necessary:
private void Form1_Load(object sender, EventArgs e)
if (CloseAfterCommandLine == true)
...process the form.....
Now this application has both Console and Winform.