Search code examples
windowswinapifile-association

How to ask Windows to open an external file based on file association?


Using Win32-specific APIs, is there an easy way to start an external application to open a file simply by passing in the path/name of the file?

For example, say I have a file called C:\tmp\image.jpg. Is there a single API that I can call to tell Windows to open the application associated with .jpg files? Without having to do a bunch of registry lookups?

I thought I remembered doing this many years ago, but I cannot find it.


Solution

  • ShellExecute

    Performs an operation on a specified file.

    Syntax

    C++

    HINSTANCE ShellExecute(
      _In_opt_ HWND    hwnd,
      _In_opt_ LPCTSTR lpOperation,
      _In_     LPCTSTR lpFile,
      _In_opt_ LPCTSTR lpParameters,
      _In_opt_ LPCTSTR lpDirectory,
      _In_     INT     nShowCmd
    );
    

    Parameters

    ...

    nShowCmd [in]

    Type: INT

    The flags that specify how an application is to be displayed when it is opened. If lpFile specifies a document file, the flag is simply passed to the associated application. It is up to the application to decide how to handle it. These values are defined in Winuser.h...