Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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:ConsoleApplicationConsoleApplication.exe
Hello
C:ConsoleApplication\_

In case of windows application its actually:

C:WindowsApplicationWindowsApplication.exe
C:WindowsApplicationHello
_

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:WindowsApplicationWindowsApplication.exe
Hello
C:WindowsApplication\_

solution:

As a result I'm running my application as

C:WindowsApplicationstart /wait WindowsApplication.exe
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
205 views
Welcome To Ask or Share your Answers For Others

1 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.

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...