如何创建一个 C# 应用程序来决定自己是显示为控制台还是窗口应用程序? [英] How do I create a C# app that decides itself whether to show as a console or windowed app?
问题描述
有没有办法启动具有以下功能的 C# 应用程序?
Is there a way to launch a C# application with the following features?
- 它通过命令行参数确定它是窗口应用程序还是控制台应用程序
- 当它被要求窗口化时不显示控制台,当它从控制台运行时不显示 GUI 窗口.
例如,
myapp.exe /help
会输出到您使用的控制台上的 stdout,但
would output to stdout on the console you used, but
myapp.exe
本身会启动我的 Winforms 或 WPF 用户界面.
到目前为止,我所知道的最好的答案是使用两个独立的 exe 并使用 IPC,但这感觉真的很糟糕.
by itself would launch my Winforms or WPF user interface.
The best answers I know of so far involve having two separate exe and use IPC, but that feels really hacky.
为了获得上述示例中描述的行为,我有哪些选择和权衡取舍?我也乐于接受特定于 Winform 或 WPF 的想法.
What options do I have and trade-offs can I make to get the behavior described in the example above? I'm open to ideas that are Winform-specific or WPF-specific, too.
推荐答案
使应用成为常规的 Windows 应用,并在需要时即时创建控制台.
Make the app a regular windows app, and create a console on the fly if needed.
更多详情请见this链接(下面的代码)
More details at this link (code below from there)
using System;
using System.Windows.Forms;
namespace WindowsApplication1 {
static class Program {
[STAThread]
static void Main(string[] args) {
if (args.Length > 0) {
// Command line given, display console
if ( !AttachConsole(-1) ) { // Attach to an parent process console
AllocConsole(); // Alloc a new console
}
ConsoleMain(args);
}
else {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
private static void ConsoleMain(string[] args) {
Console.WriteLine("Command line = {0}", Environment.CommandLine);
for (int ix = 0; ix < args.Length; ++ix)
Console.WriteLine("Argument{0} = {1}", ix + 1, args[ix]);
Console.ReadLine();
}
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AllocConsole();
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AttachConsole(int pid);
}
}
这篇关于如何创建一个 C# 应用程序来决定自己是显示为控制台还是窗口应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!