When you create a WPF application, It sets the App.Xaml as the starting point for the application. You normally have something like this:
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="Window1.xaml">
This starting point is defined in the project properties

Well, the only thing you have to do to receive the parameters is define the event “Startup” in that App.Xaml
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="Window1.xaml"
Startup="Application_Startup">
By doing this, the event handler is automatically generated in App.xaml.cs
///
/// Interaction logic for App.xaml
///
public partial class App : Application
{
private void Application_Startup(object sender, StartupEventArgs e)
{
}
}
Well, the commandline Arguments are defined in the StartupEventArgs, as a string array

Now we have the command line args, but How to read it from the application?
This is very easy, just define a public property that get those values
///
/// Interaction logic for App.xaml
///
public partial class App : Application
{
private static string[] _CommandLineArgs = null;
///
/// Command Line Arguments sent to the application
///
public static string[] CommandLineArgs
{
get
{
return _CommandLineArgs;
}
}
private void Application_Startup(object sender, StartupEventArgs e)
{
_CommandLineArgs = e.Args;
}
}
Now to access this we just call App.CommandLineArgs anywhere in our application
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
string [] commandLineArgs = App.CommandLineArgs;
foreach(string argument in commandLineArgs)
{
MessageBox.Show(argument);
}
}
}
How to test it?
Just set the parameters you want to receive under the command line arguments in the debug tab of the project properties

That's all
0 comments:
Post a Comment