三個WINDOWS SDK函數: WinExec,ShellExecute ,CreateProcess,可以實現調用其他程式的要求。
WinExec
這個函數最簡單,只有兩個參數,原型如下:
UINT WinExec(
LPCSTR lpCmdLine, // 命令路徑
UINT uCmdShow // 顯示方式
;
使用方法如下:
WinExec("Notepad.exe", SW_SHOW); // 開啟記事本
WinExec("D:""Program Files""Test""Test.exe",SW_SHOWMAXIMIZED); // 以最大化的方式開啟Test.exe
注意:MS不建議使用這個API了。Below words is from MSDN:
Note This function is provided only for compatibility with 16-bit Windows. Applications should use the CreateProcess function. if you must use WinExec for legacy reasons, make sure the application name is enclosed in quotation marks as shown in the example below.
WinExec("""C:""Program Files""MyApp.exe"" -L -S", ...)
ShellExecute
原型如下:
HINSTANCE ShellExecute(
HWND hwnd, //父視窗控制代碼
LPCTSTR lpOperation, //操作, 開啟檔案 "edit","explore","open","find","print","NULL"
LPCTSTR lpFile, //檔案名稱,前面可加路徑
LPCTSTR lpParameters, //參數
LPCTSTR lpDirectory, //預設資料夾
INT nShowCmd //顯示方式
);
使用方法如下:
ShellExecute(NULL,"open","C:""Test.txt",NULL,NULL,SW_SHOWNORMAL); // 開啟C:"Test.txt 檔案
ShellExecute(NULL, "open", "::URL::http://www.google.com",/ NULL, NULL, SW_SHOWNORMAL); // 開啟網頁www.google.com
ShellExecute(NULL,"explore", "D:""C++",NULL,NULL,SW_SHOWNORMAL); // 開啟目錄D:"C++
ShellExecute(NULL,"print","C:""Test.txt",NULL,NULL, SW_HIDE); // 列印檔案C:"Test.txt
ShellExecute不支援定向輸出。
CreateProcess
Use below function directly:
///////////////////////////////////////////////////////////////////////////////
//
// ExecApp()
//
// Purpose: Runs the specified application (replacement for WinExec)
//
// Parameters: lpszCommandLine - [in] command line (including exe filepath)
// that is passed to CreateProcess()
// wShowCmd - [in] Specifies how app window is to be shown.
// See ShowWindow() in MSDN for possible values.
//
// Returns: BOOL - TRUE = CreateProcess() succeeded
//
BOOL ExecApp(LPCTSTR lpszCommandLine, WORD wShowCmd /*= SW_SHOWNORMAL*/)
{
BOOL rc = FALSE;
if (lpszCommandLine && (lpszCommandLine[0] != _T('"0')))
{
STARTUPINFO si = { 0 };
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = wShowCmd;
PROCESS_INFORMATION pi = { 0 };
rc = ::CreateProcess(NULL, (LPTSTR)lpszCommandLine, NULL, NULL, FALSE,
NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);
TRACE(_T("CreateProcess returned %d for <%s>"n"), rc, lpszCommandLine);
// close process and thread handles now (app will continue to run)
if (pi.hProcess)
::CloseHandle(pi.hProcess);
if (pi.hThread)
::CloseHandle(pi.hThread);
}
return rc;
}
使用這三個函數也有一些注意事項:
1、定義標頭檔
在標頭檔stdafx.h中必須定義以下兩個標頭檔:
#include <shlobj.h> // 可替換為 windows.h
#include <shellapi.h>
如果定義了標頭檔 #include <windows.h>的話就不必定義 #include <shlobj.h>了,"windows.h" 不光是包含了"shellapi.h",它還定義了許多資料類型,如果沒有這些資料類型,shellapi.h本身會出錯。
2、定義路徑
C++中所表示的路徑要用 " "" "而不是平常所用的" " ",所以以上三個函數表示路徑都為:
Disk:""Directory""...""File name