views:

1754

answers:

2
+14  Q: 

WPF Command Line

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.

+24  A: 

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();
}
Matt Hamilton
Can you interact with the console (Console.ReadLine/WriteLine) at that point?
Kieran Benton
Certainly you can call Console.WriteLine, but the output won't appear on the console from which you launched the app. I'm not sure what "Console" is in the context of a WPF application.
Matt Hamilton
In order to write to the console in which the app was launched, you need to call AttachConsole(-1), Console.Writeline(message), and then FreeConsole() when you're done.
oltman
Bam. Thanks for this answer. Perfect for my situation.
WernerCD
+2  A: 

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

e.Args.Contains("MyTriggerArg")

GeekyMonkey
thanks for the helping hand with the accepted answer.
WernerCD