我有一个 WinForm 项目,如果将某些参数传递给它,我希望它可以用作控制台应用程序。使用我从此处阅读的一些提示,我使用以下代码来完成这项工作。
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AllocConsole();
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AttachConsole(int pid);
...
if (!AttachConsole(-1))
{
AllocConsole();
}
这可行,但有一个烦人的副作用——所有输出似乎都是从后台线程生成的。当我从命令提示符运行程序时,输出会在显示输出之前显示下一个提示。
我将项目属性的输出类型设置为控制台应用程序,它解决了这个问题,但现在总是显示一个控制台窗口 - 即使它在“WinForm 模式”下运行。
有没有办法在控制台表现得像程序是当前进程并且在程序显示 WinForm 时控制台窗口不显示一样两全其美?
更新: 我很抱歉没有澄清这一点。我在 Program.cs 中的控制台和 WinForm 模式之间切换,如下所示:
// nowin is a bool that is set based on a parameter
if (nowin)
{
if (!AttachConsole(-1))
{
AllocConsole();
}
//... Console mode code here...
}
else
{
// run in window
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1(argDict));
}
最佳答案
也许我做错了,但我一直都是这样做的:
[STAThread]
public static int Main(string[] args)
{
if (args.Length > 0)
{
// run console code here
}
else
{
// start up the win form app
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
return 0;
}
关于c# - WinForm/控制台混合应用程序中的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7743387/