Working with File Type Associations

Environment: VB5, VB6, running on WIN9x/ME/XP

Overview

We all know about file type associations. It's a neat way to "Associate" a particular file extension with your application, so that every time someone double-clicks on a file having that extension, presto! The file automatically opens up in your own application! This article explains exactly how you can do the same for your own application. I've seen a number of similar articles on CodeGuru, but none clearly explain the process of file association. This article explains the process of file association, and also provides ready-to-use functions to associate your application with a particular file extension. Please note that the sample code was developed for VB, but you could easily port it to VC++, or any other language, for that matter, because most of the code consists mostly of standard Win32 API calls for setting Registry key values.

Working with the Associations

Whenever a certain file extension say, ".abd", has to be associated with a particular program, a key named ".abd" has to be created under the HKEY_CLASSES_ROOT root key in the Windows Registry. The default value is then set to a short identifier for the file type; in this case, it could be "abd_ext" (NOTE: The identifier should not have any spaces in it!). Next, another key, by the name of the identifier, is created under the HKEY_CLASSES_ROOT root key, and its default value is set to a short description of the file type (for example, "My own file type"). Under the identifier key, a key called "Defaulticon" is created, and its default value is set to the complete path of the icon that is to be shown for files having that extension. Also, under the identifier key, another key by the name of "shell" is created. This key contains all the file commands that are registered for the given file extension (as in "Open", "Print", "Preview", and so forth). Within the "shell" key, one key for each file command is created, using the name of the command, say, for example, "Open". Now, within the "Open" key (or whatever command is being set), another key, called "command" is created. The default value of this key is set to the complete path of the program to be used, along with whatever command line parameters are neccessary; for example "c:\windows\notepad.exe" "%1".

That's it! Having done all that, the file extension will be registered with the chosen program. Shown below is a screenshot taken in Regedit, showing the Registry keys and tree that are created to register the .abd file extension with the program "c:\Program files\app.exe", using the identifier abd_ext. Also, another file command, "Print", has been registered for this file type.



Click here for a larger image.

Coding the Process

The entire process of associating a file extension with a certain program is automatically performed by the "Associate_File" public function, defined in the "File_Commands.bas" module in the included source code. The function declaration is as follows:

Public Function Associate_File(Extension As String, _
       Application As String, Identifier As String, _
       Description As String, Icon As String)

Parameters


Extension: This is the extension that you want to associate your program with, for example, ".doc"
Application:      This is the entire path of your program that is to be associated with the file extension, for example, "C:\Program Files\MyApp.exe"
Identifier: The identifier of the file type, as explained above, for example, "doc_file". NOTE: This parameter should not have any spaces in between!
Description: A short description of the file type, for example, "My Text Document"
Icon: The complete path of the icon that is to be associated with the file type, for example, "C:\Icons\MyIcon.ico"

The following VB pseudo-code of the Associate_File() function demonstrates the entire process. For the entire code listing, see the accompanying source code.

Some Pseudo-code

Public Function Associate_File(Extension As String, _
       Application As String, Identifier As String, _
       Description As String, Icon As String)

CreateRegistryKey   HKEY_CLASSES_ROOT\Extension
SetRegistryValue of HKEY_CLASSES_ROOT\Extension, _
                 use default value, value= 
Identifier

CreateRegistryKey HKEY_CLASSES_ROOT\Identifier
SetRegistryValue  HKEY_CLASSES_ROOT, Identifier, "", _
                  REG_SZ, Description

CreateRegistryKey HKEY_CLASSES_ROOT\Identifier\DefaultIcon
SetRegistryValue  of HKEY_CLASSES_ROOT\Identifier\DefaultIcon, _
                  use default value,value= Icon

Identifier = Identifier + "\shell"
CreateRegistryKey HKEY_CLASSES_ROOT\Identifier

Identifier = Identifier + "\open"
CreateRegistryKey HKEY_CLASSES_ROOT\Identifier

Identifier = Identifier + "\command"
CreateRegistryKey HKEY_CLASSES_ROOT\Identifier
SetRegistryValue  of HKEY_CLASSES_ROOT\Identifier, _
                  use default value,value= ("Application" "%1")

End Function

Additionally, I coded the "File_Command" function to create new file commands for a particular file type, also defined in the "File_Commands.bas" module in the included source code. The function declaration is as follows:

Public Function File_Command(Extension As String, _
       Action As String, Command As String)

Parameters


Extension: This is the extension of the file type to which you want to add a file command, for example, ".doc"
Action: This is the file command that you want to add, for example, "Preview"
Command:      The complete path of the program to be used for this command, along with the appropriate command line parameters, for example, "c:\Program Files\MyApp.exe /pre %1"

The following VB pseudo-code of the File_Command() function demonstrates the entire process. For the entire code listing, see the accompanying source code.

Some Pseudo-code:

Public Function File_Command(Extension As String, _
       Action As String, Command As String)
Dim ident as String

ident=ReadRegistryKeyValue of HKEY_CLASSES_ROOT\Extension, _
                           use default value

ident=ident+"\shell\"+Action
CreateRegistryKey HKEY_CLASSES_ROOT\ident

ident=ident+"\command"
CreateRegistryKey HKEY_CLASSES_ROOT\ident

SetRegistryValue  of HKEY_CLASSES_ROOT\ident, use default value, _
                  value= 
Command

End Function

Using the Included Source Code

To utilize the included source code, all you have to do is add the "File_Commands.bas" module to your project, and call the preceding functions, passing the appropriate parameters. This will associate your application with the specified file extension. Now, every time anyone double-clicks on a file having the specified extension, it will start up your application. Your application must inspect the command line parameters passed to it in the startup module; then accordingly load the file. To access the command line parameters passed to your application, you should inspect the value of Command$ in your startup module. The following code snippet demonstrates this. For more clarity, I suggest you download the included sample project, and go through the source code.

Using the Sample Source Code

Private Sub Form_Load()
Dim path As String

On Error GoTo nofile

If Command$ <> Empty Then
    Form1.Print
    Form1.Print
    Form1.Print
    Form1.Print

    Form1.Print "Command Line Parameter passed: " + Command$
    If Left$(Command$, 1) = Chr$(34) And Right$(Command$, 1) _
                          = Chr$(34) Then
        path = Mid(Command$, 2, (Len(Command$) - 2))
    Else
        path = Command$
    End If
    Form1.Print "Path of File passed: " + path
    Form1.Print
    Form1.Print "File contents: " + vbCrLf

    Form1.Print GetFile(path)

Else
    MsgBox ("No Parameters passed!")
End If

Exit Sub
nofile:
MsgBox ("ERROR: No valid text file!")

End Sub

Private Sub Form_DblClick() Dim app_path As String Dim Icon As String app_path = App.path + "\" + App.EXEName + ".exe" Icon = App.path + "\" + "book.ico" retval = Associate_File(".abd", app_path, "abd_ext", _ "My own extension", Icon) MsgBox ("Associated the file extension .abd with this _ application!") End Sub

That's it! if you've done everything right, it should work like a breeze. For any comments or queries, you could e-mail me at Joydeep_B@Hotmail.com.

Downloads

Download demo project - 11.7 Kb
Download source - 2.39 Kb


Comments

  • very excellent

    Posted by Legacy on 12/09/2003 12:00am

    Originally posted by: kewa

    the code is very excellent this

    • Legacy CodeGuru

      Posted by joysoft on 04/06/2005 08:49am

      Very Good

      Reply
    Reply
  • ShellExecute

    Posted by Legacy on 02/04/2003 12:00am

    Originally posted by: noname

    From MSDN

    "
    This method allows you to execute any commands in a folder's context menu or stored in the registry.

    To open a folder, use either of the following calls:

    ShellExecute(handle, NULL, path_to_folder, NULL, NULL, SW_SHOWNORMAL);

    or

    ShellExecute(handle, "open", path_to_folder, NULL, NULL, SW_SHOWNORMAL);

    To explore a folder, use:

    ShellExecute(handle, "explore", path_to_folder, NULL, NULL, SW_SHOWNORMAL);

    To launch the shell's Find utility for a directory, use:

    ShellExecute(handle, "find", path_to_folder, NULL, NULL, 0);

    If lpOperation is NULL, the function opens the file specified by lpFile. If lpOperation is "open" or "explore", the function will attempt to open or explore the folder.

    With multiple monitors, if you specify the window handle and set lpOperation to "Properties", any windows created by ShellExecute may not appear in the correct position.

    To obtain information about the application that is launched as a result of calling ShellExecute, use ShellExecuteEx.

    "

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Java developers know that testing code changes can be a huge pain, and waiting for an application to redeploy after a code fix can take an eternity. Wouldn't it be great if you could see your code changes immediately, fine-tune, debug, explore and deploy code without waiting for ages? In this white paper, find out how that's possible with a Java plugin that drastically changes the way you develop, test and run Java applications. Discover the advantages of this plugin, and the changes you can expect to see …

  • Savvy enterprises are discovering that the cloud holds the power to transform IT processes and support business objectives. IT departments can use the cloud to redefine the continuum of development and operations—a process that is becoming known as DevOps. Download the Executive Brief DevOps: Why IT Operations Managers Should Care About the Cloud—prepared by Frost & Sullivan and sponsored by IBM—to learn how IBM SmartCloud Application services provide a robust platform that streamlines …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds