有没有办法启动具有以下功能的 C# 应用程序?
- 它通过命令行参数确定它是窗口应用程序还是控制台应用程序
- 当它被要求打开窗口时,它不显示控制台,并且当它从控制台运行时,它不显示 GUI 窗口。
例如,
myapp.exe /help
would output to stdout on the console you used, but
myapp.exe
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 的想法持开放态度。
使应用程序成为常规 Windows 应用程序,并根据需要动态创建控制台。
更多详情请参见这个链接 http://social.msdn.microsoft.com/Forums/en-US/Vsexpressvb/thread/875952fc-cd2c-4e74-9cf2-d38910bde613(下面的代码来自那里)
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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)