Monday, March 21

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();

[STAThread]
static void Main(string[] args)
{


Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (args.Length != 0)
Application.Run(new Form1(args));
else
{
FreeConsole();
Application.Run(new Form1());
}
}

2, In the Form1, add a new construction function to deal with parameters:
Boolean CloseAfterCommandLine;
public Form1(string[] commands)
: this()
{
Work with the parameters
CloseAfterCommandLine = true;
}
3, Modify the original Form1(void) to have CloseAfterCommandLine = false;
4, In Form1.Load, close the WinForm if necessary:
private void Form1_Load(object sender, EventArgs e)
{
if (CloseAfterCommandLine == true)
{
Console.Out.WriteLine("Bye. ");
this.Close();
return;
}
...process the form.....
}

Now this application has both Console and Winform.

Labels:

1 Comments:

At April 04, 2011 2:13 AM, Anonymous Honza said...

thanks, nicer and simpler solution!

 

<< Home