WPF - Command Line

Datetime:2017-04-15 07:07:00         Topic: WPF          Share        Original >>
Here to See The Original Article!!!

Introduction

Command line argument is a mechanism where a user can pass a set of parameters or the values to a WPF Application when it is executed. These arguments are very important to control an Application from outside, for example, if you want to open a Word document from the command prompt, then you can use this command “ C:\> start winword word1.docx ” and it will open word1.docx document.

Command line arguments are handled in Startup function. Following is a simple example, which shows how to pass command line arguments to a WPF Application. Let’s create a new WPF Application with the name WPFCommandLine.

  1. Drag one textbox from the toolbox to the design Window.
  2. In this example, we will pass a TXT file path to our Application as command line parameter.
  3. The program will read the TXT file and subsequently write all the text on the text box.
  4. XAML code given below creates a textbox and initializes it with some properties.
    <Window x:Class="WPFCommandLine.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WPFCommandLine" mc:Ignorable="d" Title="MainWindow" Height="350" Width="525">  
        <Grid>  
            <TextBox x:Name="textBox" HorizontalAlignment="Left" Height="180" Margin="100" TextWrapping="Wrap" VerticalAlignment="Top" Width="300" /> </Grid>  
    </Window>  
    
  5. Now, subscribe Startup event in an App.xaml file, as shown below.
    <Application x:Class="WPFCommandLine.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WPFCommandLine" StartupUri="MainWindow.xaml" Startup="app_Startup">  
        <Application.Resources> </Application.Resources>  
    </Application>  
    
  6. Given below is the implementation of the app_Startup event in an App.xaml.cs, which will get the command line arguments.
    using System.Windows;  
    namespace WPFCommandLine {  
        /// <summary>  
        /// Interaction logic for App.xaml  
        /// </summary>  
        public partial class App: Application {  
            public static string[] Args;  
            void app_Startup(object sender, StartupEventArgs e) {  
                // If no command line arguments were provided, don't process them if (e.Args.Length == 0) return;  
                if (e.Args.Length > 0) {  
                    Args = e.Args;  
                }  
            }  
        }  
    }  
    
  7. Now, in the MainWindow class, the program will open the TXT file and write all the text on the textbox.
  8. If some error is found there, then the program will display an error message on the textbox.
    using System;  
    using System.IO;  
    using System.Windows;  
    namespace WPFCommandLine {  
        public partial class MainWindow: Window {  
            public MainWindow() {  
                InitializeComponent();  
                String[] args = App.Args;  
                try { // Open the text file using a stream reader.  
                    using(StreamReader sr = new StreamReader(args[0])) {  
                        // Read the stream to a string, and write  
                        // the string to the text box  
                        String line = sr.ReadToEnd();  
                        textBox.AppendText(line.ToString());  
                        textBox.AppendText("\n");  
                    }  
                } catch (Exception e) {  
                    textBox.AppendText("The file could not be read:");  
                    textBox.AppendText("\n");  
                    textBox.AppendText(e.Message);  
                }  
            }  
        }  
    }  
    
  9. When the code given above is compiled and executed, it will produce a blank Window with a textbox because this program needs a command line argument. Thus, Visual Studio provides an easy way to execute your Application with command line parameters.
  10. Right click on your WPF project in Solution Explorer and select properties. It will display the Window given below.
     
  11. Select Debug option and write the file path in the command line argument.
  12. Create a TXT file with Test.txt and write some text in the file and save it on any location. In this case, the TXT file is saved on “ D:\ ” hard drive.
  13. Save the changes in your project, compile and execute your Application now. You will see the text in TextBox, which the program reads from the Text.txt file.
     
    Now, let’s try and change the file name on your machine from Test.txt to Test1.txt and execute your program again and you will see that error message in the textbox.
     

We recommend that you execute the code given above and follow all the steps to execute your Application successfully.








New