Friday, December 13, 2013

Creating file associations in NSIS installer

Introduction

File association is a common thing for all modern operating systems users. Associated files have its own unique icon (usually it looks like icon of the application they are associated with) and one can open file simply by clicking on it - program will be started automatically and file will be loaded in work environment.
Our  goal is to create NSIS script that will do all the work - and after installing selected file extensions will be associated with our program.

How it works (Windows registry)

All information about file types, associations and programs is stored in HKEY_CLASSES_ROOT branch of the windows registry. To associate our application with selected file extension we need to create two sub keys: first one for extension we want register and second one for our application (rule of how to pass file name from shell to program).
For example: imagine we have application that is called "AwesomeProgram.exe", and file extension ".apf " which we want associate with it. In this case first key that need to be created must be the same as extension (with dot!). Set default value of this key to any string you want - good choice is our application name. So, let it be AwesomeProgram.
The second key must be named exactly as extension key default value (AwesomeProgram in our case).
There are two keys exported from registry:
So, when user double click on MyData.apf file, windows search registry and found, that apf files must be opened using AwesomeProgram. Then it uses shell open command, passing path to file MyData.apf as %1 parameter.
That's all, now just two simple steps left to make it work.

Application 

One obvious thing we need to do is to add some command options parsing possibilities to our program - when running from command line with "-f path\to\file.apf" keys it must open file immediately after loading.
Second, not so obvious, thing is that when started by this way (user clicking on file in some folder of his computer), working directory of the application will be set to file location. So you need be sure that you always use full paths for all files you need - shared dlls, resource files, help files, translation files and so on. The best way to do it is to save installation location in registry (you can do it easily with NSIS), and  read it when applications starts before doing anything else.


NSIS

Finally, fun part. You can do it with, literally, two lines of code in NSIS script.

That's all! Don't forget to delete created keys in uninstall section (using DeleteRegKey NSIS command).

No comments:

Post a Comment