username username - 3 months ago 35
C# Question

Difference between console and winforms applications when running from cmd

I have a winforms application that sometimes used from the command line.
Here is the code (simplified of course):

[STAThread]
static void Main()
{
AttachConsole(ATTACH_PARENT_PROCESS);
Console.WriteLine("Hello");

/*Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());*/
}


If that was a console application the output could be:

C:\ConsoleApplication\ConsoleApplication.exe
Hello
C:\ConsoleApplication\_


In case of windows application its actually:

C:\WindowsApplication\WindowsApplication.exe
C:\WindowsApplication\Hello
_


Can anyone tell me why do we have such difference and is it possible to make my windows application to behave like console when running from cmd?

edit:

I want my windows application to behave like console when running from cmd:

C:\WindowsApplication\WindowsApplication.exe
Hello
C:\WindowsApplication\_


solution:

As a result I'm running my application as

C:\WindowsApplication\start /wait WindowsApplication.exe

Answer

Yes. The difference is that cmd.exe is aware of the kind of executable. It knows to wait for the process to terminate when it is a console mode app. It does not wait when it is a regular Windows gui app. Trusting that it will create its own window. So it displays the command prompt again, your output gets appended to that. You'll also have trouble using Console.ReadLine() btw.

You'd have to start your program with start /wait yourapp.exe to force cmd.exe to wait. Calling AllocConsole() instead is the only universal fix. Also takes care of creating the console when your app gets started from a shortcut.

Comments