Answers:
首先,在您的App.xaml文件顶部找到此属性并将其删除:
StartupUri="Window1.xaml"
这意味着该应用程序不会自动实例化您的主窗口并显示它。
接下来,在您的App类中重写OnStartup方法以执行逻辑:
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();
}
.NET 4.0+的上述解决方案的组合,并输出到控制台:
[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);
}
在MainWindow中更改构造函数以接受参数:
public partial class MainWindow : Window
{
public MainWindow(StartupEventArgs e)
{
InitializeComponent();
}
}
并且不要忘记删除:
StartupUri="MainWindow.xaml"
您可以在app.xaml.cs
文件中使用以下内容:
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
}
}