C#应用程序同时支持GUI模式和命令行模式
前言
最近写了一个应用程序,需要同时支持命令行模式和GUI模式。网上查了一下资料,这里把相关关键的点记录一下,便于以后使用,也希望能够帮助一些人。
关键点
- 设置项目为console 模式
如果项目默认不是命令行模式,可以通过项目属性来修改。
- 声明Windows API
private static extern IntPtr _GetConsoleWindow();
[DllImport("kernel32.dll")]
private static extern bool AttachConsole(int dwProcessId);
private const int ATTACH_PARENT_PROCESS = -1;
[DllImport("kernel32.dll")]
public static extern Boolean FreeConsole();csharp
- 在Main 函数添加Code
static void Main(string[] args)
{
AttachConsole(ATTACH_PARENT_PROCESS);
// if we have paramenters, then, it's console mode
if (args.Length > 0)
{
Console.WriteLine("Here we are in console mode");
} else {
var consoleHandle = _GetConsoleWindow();
// run GUI and start forms
if (consoleHandle == IntPtr.Zero || AppDomain.CurrentDomain.FriendlyName.Contains(".vshost"))
{
FreeConsole();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
else
{
System.Console.WriteLine("console mode, but no parameters.");
}
}
}
参考
[1]. https://stackoverflow.com/questions/493536/can-one-executable-be-both-a-console-and-gui-application
[2]. https://stackoverflow.com/questions/9618804/how-to-close-open-console-within-c-sharp-using-win32-calls