Click here to Skip to main content
Click here to Skip to main content

Associate File Extension with Shell OPEN command and Application

By , 22 Jun 2000
 
<!-- Download Links -->
  • Download source files - 3 Kb
  • Download demo project - 17 Kb
  • <!-- Main HTML starts here -->

    Introduction

    This source contains a class CGCFileTypeAccess that can associate a file extension with a program.

    The association allows a new instance of the program to be activated when the icon is clicked upon in the Windows Explorer window. The full file path to the file will be sent to the program on the command line.

    The Open command also appears on the shell context menu for the file type. Selection of the open command from the context menu sends the file on the command line to a new instance of the program.

    An example of associating a file extension using the class would be done as follows, and can be found in the InitInstance of the demo program:

    CGCFileTypeAccess TheFTA;
    
    // get full file path to program executable file
    TCHAR	szProgPath[MAX_PATH * 2];
    ::GetModuleFileName(NULL, szProgPath, sizeof(szProgPath)/sizeof(TCHAR));
    
    CString csTempText;
    
    TheFTA.SetExtension("CGFILETYPETEST");
    
    // just pass file path in quotes on command line
    csTempText  = szProgPath;
    csTempText += " \"%1\"";
    TheFTA.SetShellOpenCommand(csTempText);
    TheFTA.SetDocumentShellOpenCommand(csTempText);
    
    TheFTA.SetDocumentClassName("CGFileType.Document");
    
    // use first icon in program
    csTempText  = szProgPath;
    csTempText += ",0";
    TheFTA.SetDocumentDefaultIcon(csTempText);
    
    // set the necessary registry entries	
    TheFTA.RegSetAllInfo();
    

    The relevant registry entries are all under HKEY_CLASSES_ROOT. The two primary root keys are .'FileExtension' and 'Document Class Name'. Keys and values underneath these two primary keys control the file association and the shell open command.

    The demo program will execute the file association code listed above. After it has been run at least once, each time you 'open' one of the associated file types, the program will display the file path from the command line in a message box.

    License

    This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

    A list of licenses authors might use can be found here

    About the Author

    Blake V. Miller
    Web Developer
    United States United States
    No Biography provided

    Sign Up to vote   Poor Excellent
    Add a reason or comment to your vote: x
    Votes of 3 or less require a comment

    Comments and Discussions

     
    You must Sign In to use this message board.
    Search this forum  
        Spacing  Noise  Layout  Per page   
    QuestionGet path of a file clicked upon in windows explorer.memberMahdi Nejadsahebi14-Nov-12 21:22 
    thanks for your good article
    i want to know how can i get the path of a file selected in windows explorer.
    i work with visual studio 2010
    in fact i want load files in my application when the user clicks on that.
    like image viewer or notepad.
     
    thanks again
    GeneralMy vote of 5memberMahdi Nejadsahebi14-Nov-12 21:09 
    it's great i really need it
    thanks again
    Questionwin7memberMember 80653887-Dec-11 23:17 
    Hi, this works great for me on xp but the same code fails to add anyhting to the registry in windows 7. I have the correct access rights etc. Any Ideas?
    QuestionHow to change the default icon indexmemberkrishnakumartm27-Jun-11 0:22 
    Hi,
    The methods works perfectly. But it will set the icon as the application icon, because we are passing the default index as "0". But don't wan to set the application icon to file, i want the different icon as file icon. How to identify the icons index from the exe and set.
     
    Please help me..
    ----------------------------
    KRISHNA KUMAR T M

    GeneralDoesn't workmemberdpreznik12-May-11 4:01 
    Could you tell me why this solution doesn't work for me? When I click on my document icon in Windows Explorer, it is opened with the older version of the program. I don't have HKCU\Software\Microsoft\Windows\Current Version\Explorer\FileExts\.txt\UserChoice in my registry. I use Windows XP.
    Icons do change though, after I added SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, 0, 0);
     
    Thanks.
    GeneralDoes not work if the user has specified another default applicationmemberdragomir5-Mar-09 6:20 
    If the user has specified another default application (via the 'Always Open With' dialog), this code does not work. In this case you need to delete the key stored under HKCU\Software\Microsoft\Windows\Current Version\Explorer\FileExts\.txt\UserChoice
    QuestionOpen file errormemberRui Frazão26-Dec-06 6:51 
    I have tried to open file, using CStdioFile::Open with options CFile::modeRead | CFile::shareDenyNone, but gives an error.
    The message error is strange "No error occurred"
    What could be?
    Tks
    GeneralDelphi applicationsmemberSyhon23-Nov-06 21:12 
    Ok - this may be irrelevant but does anyone know how to do a similar thing inside a Delphi project? I am a newbie and trying to make my Delphi application automatically recognise file types as its own on Windows explorer. Sigh | :sigh:
     
    http://theprecociousone.spaces.live.com/

    GeneralCool... now how do you receive the open command...memberM i s t e r L i s t e r16-Oct-06 12:53 
    Great article, I have done what you suggested and I can get my application to receive the file name when the user clicks on the file and my application is NOT running.
     
    However, when my application is running and the user clicks on a file, my application does not receive any notification that a file open command was issued ?
     
    Any ideas ?
    GeneralRe: Cool... now how do you receive the open command...memberBadJerry2-Sep-09 0:04 
    Did you find out? I am interested if you have the answer!
    GeneralSimple C# versionmembercristiscu21-Jul-06 9:14 
    Usefull stuff, Blake! Here is a simple C# version, to be adapted to your needs (check extension pre-conditions etc):
     

    using Microsoft.Win32;
     
    // Associate file extension with progID, description, icon and application
    public static void Associate(string extension, string progID, string description, string icon, string application)
    {
       Registry.ClassesRoot.CreateSubKey(extension).SetValue("", progID);
       if (progID!=null && progID.Length>0)
          using (RegistryKey key = Registry.ClassesRoot.CreateSubKey(progID))
          {
             if (description!=null)
                key.SetValue("", description);
             if (icon!=null)
                key.CreateSubKey("DefaultIcon").SetValue("", ToShortPathName(icon));
             if (application!=null)
                key.CreateSubKey(@"Shell\Open\Command").SetValue("", ToShortPathName(application) + " \"%1\"");
          }
    }
     
    // Return true if extension already associated in registry
    public static bool IsAssociated(string extension)
    {
       return (Registry.ClassesRoot.OpenSubKey(extension, false)!=null);
    }
     
    [DllImport("Kernel32.dll")]
    private static extern uint GetShortPathName(string lpszLongPath, [Out] StringBuilder lpszShortPath, uint cchBuffer);
     
    // Return short path format of a file name
    private static string ToShortPathName(string longName)
    {
       StringBuilder s = new StringBuilder(1000);
       uint iSize = (uint) s.Capacity;
       uint iRet = GetShortPathName(longName, s, iSize);
       return s.ToString();
    }

     
    Call pattern:
     

    if (!IsAssociated(".ext"))
       Associate(".ext", "ClassID.ProgID", "ext File", "YourIcon.ico", "YourApplication.exe");


     

    QuestionRe: Simple C# versionmemberFrEaK_CH25-Sep-06 7:35 
    Hi
     
    I have a question about the call pattern:
     
    if (!IsAssociated(".ext"))
    Associate(".ext", "ClassID.ProgID", "ext File", "YourIcon.ico", "YourApplication.exe");
     

    From where do I get the value ClassID.ProgID? What is that? Confused | :confused:
     
    Thank you,
    Dominik
    AnswerRe: Simple C# versionmembercristiscu26-Sep-06 15:27 
    ClassID.ProgID is the identifier of an ActiveX/COM component (see spec).
     
    I'm not sure, but it seems that an application must be registered as COM to make this kind of file association possible Confused | :confused: (?)
    GeneralLong files namesmemberKetinla26-Jan-06 0:21 
    I had, like others in this thread, the "long files names" problem.
    If the executable file was in a long path, the launched document is passed as argument in 8.3 format to the program.
     
    It was, as others said, caused by the lake of quotes arround the executable file name.
     
    Just in case, for others, it works by replacing :
     
    // just pass file path in quotes on command line
    csTempText = szProgPath;
    csTempText += " \"%1\"";
     
    by
     
    csTempText.Format("\"%s\" %s",szProgPath,"\"%1\"");
     
    Wich adds quotes arround the executable path.
     
    By this way, if the executable file is in long file name path or not, windows will pass the good long file name of the document in m_lpCmdLine

    Questionhow to check...membercreative0027-Nov-05 20:20 
    OK, every thing is fine. but can you help me finding a way to check the association?
    i have to check the association for an extention first with my app. if it is associated with some other app, i have to prompt user and then register it with app if wanted.
     
    Thanx,
     
    Ahmed: a dreaming soul.
    GeneralSetDocumentDefaultIconmemberehh15-Nov-05 7:49 
    thanks for the great discussion.
    i have a beginner's question: what determines the icon index sent to SetDocumentDefaultIcon()?
    i understand that the application's icon is 0, but that's about it.
    if you know of a tutorial describing how to set these icon-document/application associations, i'd appreciate it.
    thanks,
    ed

    GeneralRe: SetDocumentDefaultIconmemberBlake V. Miller24-Nov-05 9:06 
    It is EXACTLY the order they are located in the resources.
     
    You have to carefully order the ICON statments in the RC file if you want the icons to have a particular index.
     
    So, when the index is set to 0, it is typically because the desired icon is the first one, or in some cases, the only one in the EXE file.
     
    If you wanted the third icon in the EXE file's resources to be the applcication icon, then use an index of 2, for exmaple.

    GeneralThanks a lot...memberSreekanth Muralidharan13-Oct-05 19:07 
    This was a very useful information for my running project. Thanks a lot..
    Regards
     
    Sreekanth Muralidharan,
    Corporate Systems Consultant [Embedded Systems],
    INDIA
    QuestionHow to tell the explorer refresh the icon?memberMichael Leung24-Jul-05 1:36 
    I noticed that after a file type was registered. One-clike on the files with the spec type direct to our program as predicted. But if the file type was associated by another program before we take the change. The file's icon will not refresh to the one we specified automatically in the Explorer. Is there any way to tell windows do that for us?
     
    Best Regards,
    Michael Leung
    AnswerRe: How to tell the explorer refresh the icon?memberpo.coulet14-Sep-05 2:51 
    use SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, 0, 0);
     

     
    Pierre
    GeneralRe: How to tell the explorer refresh the icon?memberMandrago10-Jul-07 2:44 

    thx, its working,
     
    best regards
    GeneralRe: How to tell the explorer refresh the icon?membervigylant18-Jan-09 7:46 
    Thank you very much, this worked great Big Grin | :-D
    QuestionMultiple Files TOgether ???membertot2ivn18-Feb-05 0:16 
    Smile | :) How can we pass all the selected files to a running application ??
    When I use open command, each file opens a new App. window.
     
    ie. I'd like to write a program like WinMedia Player. We Right-Click --> "Add to Now Playing List" : all the selected files are added to only ONE App. window.
     
    Please help me out this problem, I desperately need it.
    Thanks so much !!
     
    A true luv is obviously eternal !!
    AnswerRe: Multiple Files TOgether ???memberBlake V. Miller24-Feb-05 16:12 
    If you completely control the program then what you do is actualy run another copy of the program. The second copy of the program passes the file to the first copy of the program and then exits. You can use WM_COPYDATA or else a memory mapped file to pass the data or some other means of interprocess communication. You also pass a flag on the command line to the program so you can disntinguish that the intention is to pass the file from the second program to the first program. This way, if the user actually starts your program with his own command and passes a file, you DO get a second copy running the second file, as the user would expect. You can't force a program to accept more than one file if it was not originaly designed to do so. I think there might be a sample of passing a file from one instance of a program to another on this website.

    GeneralRe: Multiple Files TOgether ???membertot2ivn24-Feb-05 17:47 
    Thanks Mr.Miller, I'll try your way.
     
    There are still many things eternal !!

    General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

    Permalink | Advertise | Privacy | Mobile
    Web02 | 2.6.130617.1 | Last Updated 23 Jun 2000
    Article Copyright 2000 by Blake V. Miller
    Everything else Copyright © CodeProject, 1999-2013
    Terms of Use
    Layout: fixed | fluid