Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 284
Stéphane Avatar asked Dec 03 '22 08:12

Stéphane


2 Answers

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...

like image 66
Igal Serban Avatar answered Jan 05 '23 11:01

Igal Serban


ShellExecute is the function you're looking for. It can handle both executable types and registered file types, and perform all sorts of actions (verbs) on the file, depending on what it supports.

The syntax is:

HINSTANCE ShellExecute(
    HWND hwnd,            // handle to owner window.
    LPCTSTR lpOperation,  // verb to do, e.g., edit, open, print.
    LPCTSTR lpFile,       // file to perform verb on.
    LPCTSTR lpParameters, // parameters if lpFile is executable, else NULL.
    LPCTSTR lpDirectory,  // working directory or NULL for current directory.
    INT nShowCmd          // window mode e.g., SW_HIDE, SW_SHOWNORMAL.
);

Consult your friendly neighborhood MSDN documentation for more details.

like image 40
paxdiablo Avatar answered Jan 05 '23 11:01

paxdiablo