Using Command-line Parameters In WPF


If you need to read command-line parameters within your WPF application, your first inclination (if you are like me) might be to go looking for the Main method. Of course, you won't find a "Main" method in a WPF application. Instead, start looking at the App.xaml file.

By the way, for the rest of this post, I'll presume you will be using command line switches like the following:

myapplication /key1 value1 /key2 value2

To begin, you will need to add an event handler to the App.xaml file for the Startup event. After that, your App.xaml file might look something like this:

<Application x:Class="WpfApplication1.App"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  StartupUri="Window1.xaml" Startup="AppStartup">
  <Application.Resources>
  </Application.Resources>
</Application>

(Notice the "Startup" attribute on line 4)

Your event handler's signature (in the App.xaml.cs) should look like this:

void AppStartup(object sender, StartupEventArgs e)
[more]

The StartupEventArgs class provides a string array property called "Args" that will hold all of the familiar parts of the command line arguments you are used to parsing in the "Main" method of a Windows Forms application. You can parse the arguments in the event handler and store them in a static Hashtable for other parts of the application to access. The App class might look like this:

public partial class App : Application
{
  public static Hashtable CommandLineArgs = new Hashtable();

  void AppStartup(object sender, StartupEventArgs e)
  {
    if (e.Args.Length == 0)
      return;
    string key = null;
    foreach (string arg in e.Args)
    {
      if (arg.StartsWith("/"))
      {
        //this is a key
        key = arg;
      }
      else
      {
        //should be a value
        if (key == null)
          throw new Exception("The command line arguments are malformed.");
        CommandLineArgs.Add(key, arg);
        key = null;
      }
    }
  }
}

Of course, if you require that your command line arguments are formatted differently, you will need to change the event handler to meet your needs. However, after you have your parsing figured out, you can access the arguments from within a WPF window like so:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
  foreach (string k in App.CommandLineArgs.Keys)
    lblArguments.Content += k + " = " + App.CommandLineArgs[k] + "\n";
}

The resulting output should look like this:

WPFCommandLineArgs

The take away from all of this should be that WPF allows you to handle startup differently than a "regular" application. The App class is where you can catch the events associated with startup. If you are trying to figure out how something works in WPF, try looking for an event you can handle. Most of what you could do with Windows Forms applications can still be done; it's just done differently.