三个WINDOWS SDK函数: WinExec,ShellExecute ,CreateProcess,可以实现调用其他程序的要求。
WinExec 注意: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
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