Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Windows Presentation Foundation Development Cookbook

You're reading from   Windows Presentation Foundation Development Cookbook 100 recipes to build rich desktop client applications on Windows

Arrow left icon
Product type Paperback
Published in Feb 2018
Publisher Packt
ISBN-13 9781788399807
Length 524 pages
Edition 1st Edition
Arrow right icon
Author (1):
Arrow left icon
Kunal Chowdhury Kunal Chowdhury
Author Profile Icon Kunal Chowdhury
Kunal Chowdhury
Arrow right icon
View More author details
Toc

Table of Contents (18) Chapters Close

Title Page
Copyright and Credits
Packt Upsell
Contributors
Preface
1. WPF Fundamentals FREE CHAPTER 2. Using WPF Standard Controls 3. Layouts and Panels 4. Working with Data Bindings 5. Using Custom Controls and User Controls 6. Using Styles, Templates, and Triggers 7. Using Resources and MVVM Patterns 8. Working with Animations 9. Using WCF Services 10. Debugging and Threading 11. Interoperability with Win32 and WinForm 1. Other Books You May Enjoy Index

Passing arguments to WPF applications


The command-line arguments are used to take optional parameters or values from the user, while launching the application. These are generally used to perform specific commands on the application from the outside.

In this recipe, we will learn how to pass command-line arguments to a WPF application.

Getting ready

To get started, open the Visual Studio IDE and create a WPF application project called CH01.CommandLineArgumentDemo.

How to do it...

Now follow these steps to let the application support command line arguments and perform actions based on those:

  1. 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> 
  1. 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.

 

  1. 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> 
  1. 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.
  2. 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();  
    } 
} 
  1. 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.

 

  1. 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
  1. This will launch the MainWindow of our application, with this screen:
  2. 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
  1. This will launch the OtherWindow of the application, instead of the MainWindow:

How it works...

The OnStartup(StartupEventArgs e) method signature contains StartupEventArgs as a method parameter. It contains a property, Args, that returns a string array of the command line arguments that were passed to the application. If no command line arguments were passed, the string array will have zero items in it.

Now, by checking the condition, we launch the desired window that we want to show to the user. You can also take arguments such that the application launches in normal mode, maximized mode, or minimized. You can also use it to open the application as hidden, in some specific cases.

There's more...

As we have seen how to launch the WPF application from the command line by passing the arguments, let's learn how to do this from Visual Studio itself to launch it in debug mode.

To pass a command line argument to your WPF application from Visual Studio in debug mode, right-click on the project node and click Properties from the context menu entry. This will open the project properties. Now navigate to the Debug tab. Please refer to the following screenshot:

Under Start options, enter /other as the command line arguments. Now run the application in debug mode by pressing F5. You will see that the OtherWindow opens on the screen. To launch the MainWindow, just remove the /other argument from the project properties mentioned earlier and run the application again. This time you will see that the MainWindow opens instead of the OtherWindow.

You have been reading a chapter from
Windows Presentation Foundation Development Cookbook
Published in: Feb 2018
Publisher: Packt
ISBN-13: 9781788399807
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime
Visually different images