WPF 命令行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/426421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF Command Line
提问by bingles
I am trying to create a WPF application that takes command line arguments. If no arguments are given, the main window should pop up. In cases of some specific command line arguments, code should be run with no GUI and exit when finished. Any suggestions on how this should properly be done would be appreciated.
我正在尝试创建一个采用命令行参数的 WPF 应用程序。如果没有给出参数,则应弹出主窗口。在某些特定命令行参数的情况下,代码应该在没有 GUI 的情况下运行并在完成后退出。任何有关如何正确完成此操作的建议将不胜感激。
回答by Matt Hamilton
First, find this attribute at the top of your App.xaml file and remove it:
首先,在 App.xaml 文件顶部找到此属性并将其删除:
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:
接下来,重写 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();
}
回答by GeekyMonkey
To check for the existence of your argument - in Matt's solution use this for your test:
要检查您的论点是否存在 - 在 Matt 的解决方案中,将其用于您的测试:
e.Args.Contains("MyTriggerArg")
e.Args.Contains("MyTriggerArg")
回答by Kurt Van den Branden
A combination of the above solutions, for .NET 4.0+ with output to the console:
上述解决方案的组合,用于 .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);
}
Alter the constructor in your MainWindow to accept arguments:
更改 MainWindow 中的构造函数以接受参数:
public partial class MainWindow : Window
{
public MainWindow(StartupEventArgs e)
{
InitializeComponent();
}
}
And don't forget to remove:
并且不要忘记删除:
StartupUri="MainWindow.xaml"
回答by Satish Tatikonda
You can use the below in app.xaml.cs
file :
您可以在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
}
}