WPF 命令行

我正在尝试创建一个 WPF 应用程序,它接受命令行参数。如果没有给出参数,主窗口应该会弹出。在某些特定的命令行参数的情况下,代码应该在没有 GUI 的情况下运行,并在完成时退出。如果有任何关于如何正确完成这项工作的建议,我们将不胜感激。

25911 次浏览

First, find this attribute at the top of your App.xaml file and remove it:

StartupUri="Window1.xaml"

That means that the application won't automatically instantiate your main window and show it.

Next, override the OnStartup method in your App class to perform the logic:

protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);


if ( /* test command-line params */ )
{
/* do stuff without a GUI */
}
else
{
new Window1().ShowDialog();
}
this.Shutdown();
}

To check for the existence of your argument - in Matt's solution use this for your test:

e.Args.Contains("MyTriggerArg")

You can use the below in app.xaml.cs file :

private void Application_Startup(object sender, StartupEventArgs e)
{
MainWindow WindowToDisplay = new MainWindow();


if (e.Args.Length == 0)
{
WindowToDisplay.Show();
}
else
{
string FirstArgument = e.Args[0].ToString();
string SecondArgument = e.Args[1].ToString();
//your logic here
}
}

A combination of the above solutions, for .NET 4.0+ with output to the console:

[DllImport("Kernel32.dll")]
public static extern bool AttachConsole(int processID);


protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);


if (e.Args.Contains("--GUI"))
{
// Launch GUI and pass arguments in case you want to use them.
new MainWindow(e).ShowDialog();
}
else
{
//Do command line stuff
if (e.Args.Length > 0)
{
string parameter = e.Args[0].ToString();
WriteToConsole(parameter);
}
}
Shutdown();
}


public void WriteToConsole(string message)
{
AttachConsole(-1);
Console.WriteLine(message);
}

Alter the constructor in your MainWindow to accept arguments:

public partial class MainWindow : Window
{
public MainWindow(StartupEventArgs e)
{
InitializeComponent();
}
}

And don't forget to remove:

StartupUri="MainWindow.xaml"