Wednesday, 5 September 2012

Pass Command Line Arguments/Parameters to a WPF Application

Passing parameters from the command line to a WPF application is not as straightforward as doing the same in WinForms. It's a multiple step process, which I've detailed below.
  1. Edit the app.xaml.cs like this:
      using System;
      using System.Collections.Generic;
      using System.Configuration;
      using System.Data;
      using System.Linq;
      using System.Windows;
      namespace Tool
          /// <summary>
          /// Interaction logic for App.xaml
          /// </summary>
          public partial class App : Application
              public static string[] args;
              void OnStartUp(object sender, StartupEventArgs e)
                  if (e.Args.Length > 0)
                      args = e.Args;
  2. Edit the app.xaml like this:
      <Application x:Class="Tool.App"
                   StartupUri="MainWindow.xaml" Startup="OnStartUp">
  3. Edit MainWindow.xaml.cs like this:
     public MainWindow()
         if (App.args != null && App.args.Length > 0)
           //Do Something here with Command Line Arguments/Parameters
Remember that you can pass paremeters/arguments from visual studio for debugging purposes.
  1. Right Click on Project and Select Properties.
  2. Go to Debug tab.
  3. Set Command Line arguments, see screenshot below.

No comments:

Post a Comment