Stephan Pich
Stephan Pich

Reputation: 301

What do I do to in a WPF Application when I want to start it by opening a file

Hi I'm writing a simple WPF to show binary file content.

So I'd like to start the application when I try to open a file.

But I have no idea where to start.

How and where do I get the data of the file that is to be opened?

I tried reading commandline args from the

StartupEventArgs e

and from

Environment.GetCommandLineArgs();

bot return empty string arrays.

I can already process the file and open them during runtime but have no idea how to open one at start.

Does anyone have an idea where to start.

Thanks in advance

Upvotes: 0

Views: 1012

Answers (1)

huserben
huserben

Reputation: 1096

When you select your WPF application in the File -> Open With dialog you will get it as parameter passed to your Application.

So if you're setting up your App.xaml like this:

<Application x:Class="WpfApp1.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:local="clr-namespace:WpfApp1"
         StartupUri="MainWindow.xaml"
         Startup="Application_Startup">
...
</Application>

You can listen in your App.xaml.cs for the Startup Event:

  private void Application_Startup(object sender, StartupEventArgs e)
  {
     foreach (var arg in e.Args)
     {
        MessageBox.Show(arg);
     }
  }

For demo purpose I just output all the arguments in a message box as it's hard to attach a debuger to the process in time. Now if we open any file with that app: Open File With Open with WPF App

We will see this:

Argument Message Box

So the file path will be passed in as the first parameter to the application. From there you can do with it whatever you need to.

If you would associate a filetype with your application you'll get the same behavior via double-clicking the file. If your application will be installed using an installed like Wix you would have the option to associate certain filetypes as part of the installation directly.

Upvotes: 2

Related Questions