Traditionally, handling command-line args in an app has been a simple case of reading arguments from the “int main()” function (or equivalent). In WPF this changes somewhat.
The usual setup is that you have your App.xaml.cs, which loads your initial window. While it’s the former that has access to the arguments, it’s the latter that is likely to use them. So the steps are:
- In App.xaml.cs, catch the event that gives you the args.
- Store them somewhere.
- Access them from your main window.
Here’s one way to do it (demonstrating a single argument). Firstly, in App.xaml.cs:
Then in the main window, you can access Application.Current.Properties to get at your args. However, if this happens to be the name of a file you want to load, you should probably wait until after your window has finished loading so that you can react to that file load (eg; give an error, display data, etc):
Launching via a double-click on a custom file type.
I created an application that supports a custom document format and I wanted a double-click on that document to open my application. I assumed that the application would open normally with the document presented as a command-line arg, but that’s not the case. Instead, it’s stored in the following tongue-twister:
So, if you revisit the OnStartup method in App.xaml.cs, you can query this location and store it in the same way you did the command-line arg:
Notice the little trick with using the “Uri” class; this is because the string you’ll see will look like this: