How to start WPF based on Arguments

In Application class there is an event "StartUp" you can use it . It provide you the args you provide through command prompt. Here is an example from MSDN:

App.xaml

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

App.xaml.cs

public partial class App : Application
{
    void App_Startup(object sender, StartupEventArgs e)
    {
        // Application is running
        // Process command line args
        bool startMinimized = false;
        for (int i = 0; i != e.Args.Length; ++i)
        {
            if (e.Args[i] == "/StartMinimized")
            {
                startMinimized = true;
            }
        }

        // Create main application window, starting minimized if specified
        MainWindow mainWindow = new MainWindow();
        if (startMinimized)
        {
            mainWindow.WindowState = WindowState.Minimized;
        }
        mainWindow.Show();
    }
}

I hope this will help.


There are 2 options to get the command line arguments
1) If you want to read the arguments OnStartup. This is good for global access of the args.

Override OnStartup in App.xaml.cs and look at the Args property of the StartupEventArgs class.

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        foreach (string arg in e.Args)
        {
            // TODO: whatever
        }
        base.OnStartup(e);
    }
}

2) Another easy way is to read the arguments from the Environment Object.

Environment.GetCommandLineArgs();

This can be used from anywhere in the application like from the Form / Page also.

Tags:

C#

Wpf