我编写的应用程序可以在命令行上运行,也可以使用WPF UI运行.
[STAThread]
static void Main(string[] args)
{
// Does magic parse args and sets IsCommandLine to true if flag is present
ParseArgs(args);
if(IsCommandLine)
{
// Write a bunch of things to the console
}
else
{
var app = new App();
app.Run(new Window());
}
}
Run Code Online (Sandbox Code Playgroud)
我将项目的输出类型设置为控制台应用程序,如果我尝试通过双击exe来执行它,我会弹出一个控制台窗口.如果未设置标志(通过命令args传入),我不想向用户显示控制台窗口.
但是,如果我将项目的输出类型设置为Windows应用程序,则双击行为很好,但是当我在控制台中运行它时,我没有控制台输出(Console.Writeline)
小智 6
创建一个WPF应用并将以下代码添加到您的App类中:
public partial class App
{
protected override void OnStartup(StartupEventArgs e)
{
if (e.Args.Length > 0)
{
List<string> lowercaseArgs = e.Args.ToList().ConvertAll(x => x.ToLower());
if (AttachConsole(ATTACH_PARENT_PROCESS))
{
// your console app code
Console.Write("\rPress any key to continue...");
Console.ReadKey();
FreeConsole();
}
Shutdown();
}
else
{
base.OnStartup(e);
}
}
private const int ATTACH_PARENT_PROCESS = -1;
[DllImport("kernel32", SetLastError = true)]
private static extern bool AttachConsole(int dwProcessId);
[DllImport("kernel32.dll")]
private static extern bool FreeConsole();
}
Run Code Online (Sandbox Code Playgroud)