温馨提示×

ShellExecute详细用法

小亿
178
2024-01-05 19:33:46
栏目: 编程语言

ShellExecute是一个Windows API函数,用于打开外部应用程序、打开URL链接或者执行系统命令。

ShellExecute的函数原型如下:

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

参数说明:

  • hwnd:指定父窗口的句柄,如果不需要指定父窗口,可以传入NULL。
  • lpOperation:指定操作类型,可以是"open"、“print”、"explore"等等。如果不需要指定操作类型,可以传入NULL。
  • lpFile:指定要打开的文件名、URL链接或者系统命令。
  • lpParameters:指定要传递给打开文件的参数,如命令行参数。如果没有参数,可以传入NULL。
  • lpDirectory:指定要打开文件的目录。如果不需要指定目录,可以传入NULL。
  • nShowCmd:指定打开文件时的显示方式,如最大化、最小化等。常见取值有SW_SHOW、SW_HIDE等。

返回值:

  • 如果函数执行成功,返回大于32的HINSTANCE句柄。如果函数执行失败,返回值取决于错误的原因。

使用ShellExecute打开外部应用程序的示例代码:

#include <Windows.h>
#include <ShellAPI.h>

int main() {
    ShellExecute(NULL, _T("open"), _T("C:\\Windows\\notepad.exe"), NULL, NULL, SW_SHOW);
    return 0;
}

使用ShellExecute打开URL链接的示例代码:

#include <Windows.h>
#include <ShellAPI.h>

int main() {
    ShellExecute(NULL, _T("open"), _T("http://www.example.com"), NULL, NULL, SW_SHOW);
    return 0;
}

使用ShellExecute执行系统命令的示例代码:

#include <Windows.h>
#include <ShellAPI.h>

int main() {
    ShellExecute(NULL, _T("open"), _T("cmd.exe"), _T("/c echo Hello World"), NULL, SW_SHOW);
    return 0;
}

需要注意的是,ShellExecute函数是一个异步操作的函数,函数调用会立即返回而不等待应用程序执行完毕。如果需要等待应用程序执行完毕再进行其他操作,可以使用ShellExecuteEx函数。

0