如何让Windows根据文件关联打开外部文件?

Sté*_*ane 4 windows winapi file-association

使用特定于Win32的API,是否有一种简单的方法可以通过传入文件的路径/名称来启动外部应用程序来打开文件?

例如,假设我有一个名为C:\ tmp\image.jpg的文件.我可以调用一个API来告诉Windows打开与.jpg文件关联的应用程序吗?无需进行一堆注册表查找?

我以为我记得多年前这样做过,但我找不到它.

Iga*_*ban 12

ShellExecute的

对指定文件执行操作.

句法

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
);
Run Code Online (Sandbox Code Playgroud)

参数

...

nShowCmd [in]

类型:INT

指定应用程序打开时如何显示的标志.如果lpFile指定文档文件,则该标志将简单地传递给关联的应用程序.由应用程序决定如何处理它.这些值在Winuser.h中定义...


pax*_*blo 6

ShellExecute是您正在寻找的功能.它可以处理可执行类型和已注册的文件类型,根据文件支持的内容对文件执行各种操作(动词).

语法是:

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.
);
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅友好邻居MSDN文档.