Now follow these steps to let the application support command line arguments and perform actions based on those:
- Open the MainWindow.xaml to add a TextBlock into the Grid panel. Replace the entire XAML content with the following lines:
<Window x:Class="CH01.CommandLineArgumentDemo.MainWindow" xmlns=
"http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Main Window" Height="200" Width="400"> <Grid> <TextBlock Text="This is 'Main Window'
of the application." HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="18" /> </Grid> </Window>
- Create a new window in the project by right-clicking on the project node and then following the context menu path Add | Window... to open the Add New Item dialog window. Give it the name OtherWindow and click the Add button. This will add OtherWindow.xaml and OtherWindow.xaml.cs into the project.
- Now open the OtherWindow.xaml and change its UI to have different text. Let's replace the entire XAML code with the following lines:
<Window x:Class="CH01.CommandLineArgumentDemo.OtherWindow" xmlns=
"http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Other Window" Height="200" Width="400"> <Grid> <TextBlock Text="This is 'Other Window' of the
application." HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="18" /> </Grid> </Window>
- Now open the App.xaml and remove the StartupUri="MainWindow.xaml". This has been done to control the launch of the proper window, based on the argument passed to the application.
- Open the App.xaml.cs and override its OnStartup method to retrieve the arguments passed to it and open the desired window based on that. Let's add the following code implementation for the OnStartup method:
protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); var args = e.Args; if (args.Contains("/other")) { new OtherWindow().Show(); } else { new MainWindow().Show(); } }
- Now build the project. Navigate to the bin\Debug folder and launch a Command Window in that location. Alternatively, you can launch a Command Window (cmd.exe) and navigate to the bin\Debug path, where your application is available.
- In the console window, enter the name of the application without passing any arguments to it, as shown in the following command:
CH01.CommandLineArgumentDemo.exe
- This will launch the MainWindow of our application, with this screen:
- Close the application window and, from the console window, enter the application name by specifying the /other argument to it, as shown in the following command:
CH01.CommandLineArgumentDemo.exe /other
- This will launch the OtherWindow of the application, instead of the MainWindow: