三个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