Dutton

How to handle Command Line Arguments in WPF Applications

I've not considered it before as up to now I haven't required it, but obviously in a WPF Application you don't have a nice

static void Main(string[] args)
{
...
}

with a useful string array of arguments like you do in a regular C# console app, so how do you access them?

In a default WPF application, the entry point to the program is the Application object. This object has an event Startup which is fired, unsurprisingly on startup of your app and contains StartupEventArgs. You can query this object to get to your arguments as follows:

public partial class App : Application
 {
   /// 
   /// A static string array containing our start-up command line arguments
   /// 
   public static string[] Args;

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

Store them in a static member and then you can access them elsewhere in your application as Apps.Args.

So far, so good. But what happens if you actually need some arguments to run, and so want to check and fail gracefully if they don't exist? I found that if I checked in my OnStartup handler, I still couldn't halt the start-up of my application on error.

Instead, I added a Loaded event handler to my MainWindow. This is fired once the Application and MainWindow have been loaded so I know I my static Args member will have been set by the time it is fired. I can do all the validation I want on my argument array and decide whether to continue execution or stop and provide an error to the user.

public MainWindow()
{
     InitializeComponent();

     // Make sure the command line arguments have been processed
     this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
}

void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    if (App.Args.Length == 1)
    {
        // everything is good, do stuff
    }
    else
    {
        // ERROR!!!
        MessageBox.Show("Not enough arguments!");
        App.Current.Shutdown();
     }
}

Share this: