首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> VC >> 關於VC++

ShellExecute 多功能應用大全:開啟文件、網頁、郵件、列印

     編輯:關於VC++

核心優勢

ShellExecute 會自動解析系統檔案關聯,無需指定完整路徑即可啟動對應應用程式。支援檔案、URL、郵件、列印、搜尋等多種動作。

常用調用範例

// 開啟應用程式
ShellExecute(m_hWnd, L"open", L"calc.exe", nullptr, nullptr, SW_SHOW);
ShellExecute(m_hWnd, L"open", L"notepad.exe", L"c:\\MyLog.log", nullptr, SW_SHOW);

// 開啟關聯文件
ShellExecute(m_hWnd, L"open", L"c:\\abc.txt", nullptr, nullptr, SW_SHOW);

// 開啟網頁
ShellExecute(m_hWnd, L"open", L"https://www.google.com", nullptr, nullptr, SW_SHOW);

// 發送郵件
ShellExecute(m_hWnd, L"open", L"mailto:user@example.com", nullptr, nullptr, SW_SHOW);

// 列印文件
ShellExecute(m_hWnd, L"print", L"c:\\abc.txt", nullptr, nullptr, SW_HIDE);

// 搜尋資料夾
ShellExecute(m_hWnd, L"find", L"d:\\folder", nullptr, nullptr, SW_SHOW);

等待程序結束:ShellExecuteEx + WaitForSingleObject

SHELLEXECUTEINFO sei = { sizeof(sei) };
sei.fMask = SEE_MASK_NOCLOSEPROCESS;
sei.lpVerb = L"open";
sei.lpFile = L"c:\\MyProgram.exe";
sei.nShow = SW_SHOW;

ShellExecuteEx(&sei);
WaitForSingleObject(sei.hProcess, INFINITE);
CloseHandle(sei.hProcess);

替代方案:CreateProcess

PROCESS_INFORMATION pi;
STARTUPINFO si = { sizeof(si) };
if (CreateProcess(L"c:\\winnt\\notepad.exe", nullptr, nullptr, nullptr,
    FALSE, 0, nullptr, nullptr, &si, &pi)) {
    WaitForSingleObject(pi.hProcess, INFINITE);
    CloseHandle(pi.hThread);
    CloseHandle(pi.hProcess);
}

顯示檔案屬性對話框

SHELLEXECUTEINFO sei = { sizeof(sei) };
sei.fMask = SEE_MASK_INVOKEIDLIST;
sei.lpVerb = L"properties";
sei.lpFile = L"c:\\";
ShellExecuteEx(&sei);

關鍵參數說明

  • lpVerb:open、print、edit、find、properties
  • nShow:SW_SHOW、SW_HIDE、SW_MAXIMIZE 等
  • 回傳值 > 32 表示成功,否則為錯誤碼
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved