Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between console and winforms applications when running from cmd

Tags:

c#

winforms

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
like image 964
username Avatar asked Dec 09 '22 05:12

username


1 Answers

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.

AllocConsole() is fairly disorienting. Consider writing a tiny console mode app that does nothing but Process.Start + WaitForExit to start your main program. Perhaps also munging the command line arguments. Now you get the blocking behavior back. If you rename the executable to mainapp.com (to start mainapp.exe) then the difference is hidden quite well, a trick that VS uses as well (devenv.exe vs devenv.com).

like image 57
Hans Passant Avatar answered Dec 11 '22 18:12

Hans Passant