Monday, September 8, 2008

Where's My Command Line?

When I first looked for the command line in a WPF application, I couldn't find it anywhere. A web search found considerable discussion of this; some of the techniques worked, some didn't, and some were much more complicated than necessary. It's really not that hard.

To start with, we need someplace to put the command line parameters. I use a global static List<string> for this. I know, globals are bad, and that's true--but in my view, it is perfectly OK to use a very small number of global variables for things that you know you'll only need one of in an application. If you don't want to do this, that's fine. Use a field/property in your main window or add it to your Application class. But here's what I have in Globals.cs:
namespace MyApplication
{
public static class Globals
{
public static List<string> Args;
}
}
Now I can reference my arguments via Globals.Args.

Filling the list is simple. All you have to do is override Application.OnStartup in App.xaml.cs and look at the System.Windows.StartupEventArgs parameter. StartupEventArgs contains an Args member, which is an array of strings containing your command line parameters. Like this:
namespace MyApplication
{
public partial class App : Application
{
...
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
Globals.Args = new List();
for (int ix = 0; ix < e.Args.GetLength(0); ++ix)
Globals.Args.Add(e.Args[ix]);
}
}
}
Now you have a nice list of parameters. The number of parameters is Globals.Args.Count, and the first argument is Globals.Args[0]. What could be easier?

No comments: