Wednesday, October 6, 2010

Command Line Arguments in WPF Applications

We may allow user to provide command line arguments to our WPF application. We might need to access these arguments to define the behavior of our system. But how can we access these arguments in our application? Generally we need to access these arguments when we start the application. But we might be interested to access them later in the lifetime of the application. WPF supports both of these requirements.

App_Startup Event Handler:
You can subscribe Startup Event to WPF Application. Command line arguments are available in Args property in StartupEventArgs. Here Args is a string array.

Let us specify the Startup event handler in App.xaml.

<Application x:Class="WPFCommandLineArguments.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Startup="App_Startup" >
<Application.Resources>

</Application.Resources>
</Application>

Now we provide the definition of App_Startup handler. Here we are just accessing all the arguments provided and displaying them in a MessageBox.

public partial class App : Application
{
void App_Startup(object sender, StartupEventArgs e)
{
foreach(string arg in e.Args)
{
MessageBox.Show(arg);
}
MainWindow mainWindow = new MainWindow();
mainWindow.Show();
}
}

In order to provide the command line paramenters, lets create a shortcut to our exe and provide some command line arguments.



Now when we run the applcation, these message box are displayed as expected:





Using Environment.GetCommandLineArguments():
When we need these arguments anywhere else in our application. We can make use of GetCommandLineArguments() in Environment. This method returns a string array so we can use this same as we used Args in previous example.


<Window x:Class="WPFCommandLineArguments.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Content="Display Command Line Arguments" Height="47"
HorizontalAlignment="Left" Margin="151,124,0,0"
Name="button1" VerticalAlignment="Top" Width="211" Click="button1_Click" />
</Grid>
</Window>


The definition for button1_Click is as follows:

private void button1_Click(object sender, RoutedEventArgs e)
{
foreach (string arg in Environment.GetCommandLineArgs())
{
MessageBox.Show(arg);
}
}

Note: The only difference between Environment.GetCommandLineArguments() and StartupArgs.Args is that the former has the name of executable (including path) as the first element of the array.

No comments: