我有一个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();
}
Run Code Online (Sandbox Code Playgroud)
这有效,但有一个恼人的副作用 - 所有输出似乎都是从后台线程生成的.从命令提示符运行程序时,输出显示输出前的下一个提示.
我将项目属性的输出类型设置为控制台应用程序,它解决了这个问题,但现在总是显示一个控制台窗口 - 即使它在'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));
}
Run Code Online (Sandbox Code Playgroud)
也许我一直在做错了,但我总是做这样的杂交:
[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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3223 次 |
| 最近记录: |