c++使用 ShellExecute 打开文件或执行程序

2018-09-17  本文已影响148人  程序员欧阳

使用 ShellExecute 打开文件或执行程序

可以使用 ShellExecute 打开文件或执行程序。

原型:

HINSTANCE ShellExecute(
  _In_opt_ HWND    hwnd,//父窗口句柄或出错时显示错误父窗口的句柄,可以为 NULL
  _In_opt_ LPCTSTR lpOperation,//操作
  _In_     LPCTSTR lpFile,//要打开的文件名、执行的程序名、浏览的文件夹等。
  _In_opt_ LPCTSTR lpParameters,//可执行程序的参数,否则为 NULL
  _In_opt_ LPCTSTR lpDirectory,//默认目录
  _In_     INT     nShowCmd//显示类型
);

lpOperation 是一个字符串,通常为:

nShowCmd 执行操作之后程序显示类型,指定该参数后运行起来的程序不一定能按照指定参数显示,只是通知程序的显示状态。类型如下:

返回值:
返回值为被执行程序的实例句柄。若返回值小于32,则表示出现错误。错误如下:

使用:

    int ret = (int)ShellExecute(NULL, _T("open"), _T("Dbgview.exe"), NULL, NULL, SW_NORMAL);//打开exe
    if (ret < 32)//检测是否指定成功
        MessageBox(_T("ERROR"));
    ret = (int)ShellExecute(NULL, _T("open"), _T("help.pdf"), NULL, NULL, SW_NORMAL);//打开指定文件,将调用默认处理的程序打开
    if (ret < 32)
        MessageBox(_T("ERROR"));
    ret = (int)ShellExecute(NULL, _T("open"), _T("https://www.baidu.com"), NULL, NULL, SW_NORMAL);//打开网址
    if (ret < 32)
        MessageBox(_T("ERROR"));
    ret = (int)ShellExecute(NULL, _T("open"), _T("c:\\windows"), NULL, NULL, SW_NORMAL);//打开文件夹
    if (ret < 32)
        MessageBox(_T("ERROR"));
    ret = (int)ShellExecute(NULL, _T("runas"), _T("cmd.exe"), NULL, NULL, SW_NORMAL);//请求管理员权限打开cmd
    if (ret < 32)
        MessageBox(_T("ERROR"));

实例:

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <shellapi.h>

int main(void)
{
    test01();
}

int test01()
{
    HINSTANCE hNewExe = ShellExecuteA(NULL, "open", "calc.exe", NULL, NULL, SW_SHOW);

    if ((DWORD)hNewExe <= 32)
    {
        printf("return value:%d\n", (DWORD)hNewExe);
    }
    else
    {
        printf("successed!\n");
    }

    printf("GetLastError: %d\n", GetLastError());
    system("pause");
    return 1;
}

上一篇 下一篇

猜你喜欢

热点阅读