views:

152

answers:

5

When you double-click on a Word document, Word is automatically run and the document is loaded.

What steps are needed to do the same thing with my C# application?

In other words, assume my application uses ".XYZ" data files. I know how to tell Windows to start my application when a .XYZ data file is double clicked. But how do I find out within my application what data file was chosen so I can load it?

+1  A: 

The arguments should contain the path to the data file.

You can tweak this behavior and pass additional arguments. Look at the example in this image. Here the file path is passed with %1.

Quicktime File Association Dialog

sjbotha
+1  A: 

I think what you are looking for is command-line arguments. If you look at the Open action for .doc for example you'll probably see something like this 'word.exe %1'. Windows will take the name of the file and substitute it in for %1 and then execute the command 'word.exe whatever.doc'. Then from within the application you can see what was passed as an argument into the program see this MSDN article for more details.

Kevin Loney
+1  A: 

I believe it is just a command-line argument that gets passed into your app. Then you can read it with Environment.GetCommandLineArgs. I know that is the case if you drag-and-drop a file onto your app. I have not done what you are describing myself but I assume it works the same way.

nshaw
+2  A: 

Granted this is a VB.NET solution, but this article has details on how to create the file association for your application in the registry and how to retrieve the command arguments when your application is fired up to do the proper file handling.

It looks easy enough to port over to C#.

Dillie-O
This is on the right track. You need to add the registry keys mentioned in your application's installer code.
Daniel
A: 

I did this in a project I was working on awhile ago and don't have the source code handy, but I believe it really came down to this:

    //program.cs
    [STAThread]
    static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        if (args.Length > 0)
        {
            //launch same form as normal or different
            Application.Run(new Form1(args));
        }
        else
        {
            Application.Run(new Form1());
        }
    }

args is empty when the application is normally started, but when you've properly linked in the association to your .xyz file, when one of those files is selected, your application will be launched with the file location as the first element of the string[]. Certainly either in program.cs or your launch form, I would add validation, but at the base level I believe this is what you need to do.

Timothy Carter