WPF Command Line

て烟熏妆下的殇ゞ 提交于 2019-11-26 07:24:50

问题


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.


回答1:


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();
}



回答2:


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

e.Args.Contains("MyTriggerArg")




回答3:


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"



回答4:


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
    }
}


来源:https://stackoverflow.com/questions/426421/wpf-command-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!