Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

c# - 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: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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...