Associating+an+application+with+a+file+type

//by Richard Russell, May 2015//

The code below associates an application with a particular file type, as indicated by its extension. The extension is specified as **Extension$** (don't forget the dot) and the command used to open files with that extension is specified as **Command$**. The code assumes that the name of the file is passed to the application as a simple command-line parameter.

The variable **ProgID$** must be unique to that particular application, and this can be most easily achieved by incorporating the extension as part of the name, as shown in the example code (i.e. the extension **.xyz** gives the ProgID **xyzfile**).

The code writes to the HKEY_CLASSES_ROOT registry hive and will only run successfully if it has administrative privileges. On Windows Vista or later, with UAC (User Account Control) enabled, this can be most easily achieved by using **Run As Administrator** (either when running the BB4W IDE or the compiled executable, as appropriate).

Use this code with care, especially as it can change the association of an existing file type - without prompting for confirmation or otherwise alerting the user.

code format="bb4w" REM!WC Windows Constants: HKEY_CLASSES_ROOT=&80000000 KEY_WRITE=&20006 REG_SZ=1

Extension$ = ".xyz" ProgID$ = "xyzfile" Command$ = """C:\Temp\MyProg.exe"" %1"

SYS "RegCreateKeyEx", HKEY_CLASSES_ROOT, Extension$, 0, "", 0, \ \                    KEY_WRITE, 0, ^key%, 0 TO ret% IF ret% THEN ERROR 100, "RegCreateKeyEx failed (ProgID)"

SYS "RegSetValueEx", key%, "", 0, REG_SZ, ProgID$, LEN(ProgID$)+1 TO ret% IF ret% THEN ERROR 100, "RegSetValueEx failed (ProgID)"

SYS "RegCloseKey", key%

SYS "RegCreateKeyEx", HKEY_CLASSES_ROOT, ProgID$ + "\shell\Open\command", 0, "", 0, \ \                    KEY_WRITE, 0, ^key%, 0 TO ret% IF ret% THEN ERROR 100, "RegCreateKeyEx failed (Command)"

SYS "RegSetValueEx", key%, "", 0, REG_SZ, Command$, LEN(Command$)+1 TO ret% IF ret% THEN ERROR 100, "RegSetValueEx failed (Command)"

SYS "RegCloseKey", key% code