WPF Command Line - Windows Presentation Foundation(WPF)

What is WPF Command Line?

Command line argument is a method where a user can pass a set of parameters or values to a WPF application when it is execute. These arguments are very essential to control an application from outside, for instance, 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 point of view is handled in Start-up function. Following is an easy instance which shows how to pass command line arguments to a WPF application. Let’s create a new WPF application with the name WPFCommandLine.

  • Drag one textbox from the toolbox to the create window.
  • In this instance, we will pass a txt file path to our application as command line parameter.
  • The program will read the txt file and then write all the text on the text box.
  • The following XAML code creates a textbox and initializes it with some properties.

  • Currently subscribe the Start-up event in App.xaml file as exposed below.

  • Given below is the implementation of the app_Startup event in App.xaml.cs which will get the command line arguments.

  • Nowadays, in the Main Window class, the program will open the txt file and write all the text on textbox.
  • If there is some error found, then the program will display an error message on textbox.

  • When the above code is compiled and executed, it will produce a blank window with a textbox because this program needs a command line argument. So Visual Studio provides an easy way to execute your application with command line parameters.
  • Right click on your WPF project in the solution explorer and choose properties; it will present the following window.

wpf_commandline

  • choose Debug option and write the file path in the Command line argument.
  • Create a txt file with Test.txt and write some text in that file and save it on any location. In this case, the txt file is saved on “D:\” hard drive.
  • Save the changes in your project and compile and execute your application now. You will see the text in Textbox which the program reads from the Text.txt file.
    output_of_commandline

Currently let’s try and change the file name on your device from Test.txt to Test1.txt and execute your program once more, then you will see that error message in the text box.
error_output_of_the_commandline

We recommend that you execute the above code and follow the entire stepladder to execute your application effectively.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Windows Presentation Foundation(WPF) Topics