问题描述
我有一个有时从命令行使用的 winforms 应用程序.这是代码(当然是简化的):
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\_
如果是 Windows 应用程序,它实际上是:
In case of windows application its actually:
C:WindowsApplicationWindowsApplication.exe
C:WindowsApplicationHello
_
谁能告诉我为什么我们有如此大的差异,是否有可能使我的 Windows 应用程序在从 cmd 运行时表现得像控制台?
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?
我希望我的 Windows 应用程序在从 cmd 运行时表现得像控制台:
I want my windows application to behave like console when running from cmd:
C:WindowsApplicationWindowsApplication.exe
Hello
C:WindowsApplication\_
解决方案:
因此我运行我的应用程序
As a result I'm running my application as
C:WindowsApplicationstart /wait WindowsApplication.exe
推荐答案
是的.不同之处在于 cmd.exe 知道可执行文件的类型.当它是控制台模式应用程序时,它知道等待进程终止.当它是一个普通的 Windows gui 应用程序时,它不会不等待.相信它会创建自己的窗口.所以它再次显示命令提示符,你的输出被附加到它上面.顺便说一句,您在使用 Console.ReadLine()
时也会遇到问题.
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.
你必须用 start/wait yourapp.exe
来启动你的程序来强制 cmd.exe 等待.调用 AllocConsole()
是唯一的通用修复方法.还负责在您的应用从快捷方式启动时创建控制台.
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() 相当迷惑.考虑编写一个小型的控制台模式应用程序,它只执行 Process.Start + WaitForExit 来启动您的主程序.也许还修改了命令行参数.现在您恢复了阻塞行为.如果将可执行文件重命名为 mainapp.com(以启动 mainapp.exe),那么差异就隐藏得很好,这是 VS 也使用的一个技巧(devenv.exe vs devenv.com).
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).
这篇关于从 cmd 运行时控制台和 winforms 应用程序之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!