在VC程序中调用exe文件或者批处理文件的方法:
一、使用system函数。
该函数可以直接使用,调用exe程序或者bat批处理程序
例如:CString strCommand("d:\\test.bat");
system(strCommand);
二、使用ShellExecute函数
该函数可以将调用的窗口隐藏或者显示。
HINSTANCE ShellExecute( HWND hwnd,
LPCTSTR lpOperation,
LPCTSTR lpFile,
LPCTSTR lpParameters,
LPCTSTR lpDirectory,
INT nShowCmd
);
三、使用CreateProcess函数
std::string strCommand = strApp + "\\PerDecodeX2ap.exe";
PROCESS_INFORMATION pi;
STARTUPINFO si;
//初始化变量
memset(&si,0,sizeof(si));
si.cb=sizeof(si);
si.wShowWindow = SW_HIDE;
si.dwFlags = STARTF_USESHOWWINDOW;
char buff[256];
sprintf(buff,"%s",strCommand.c_str());
BOOL fRet=CreateProcess(NULL,
buff,
NULL,
NULL,
FALSE,
NORMAL_PRIORITY_CLASS|CREATE_NO_WINDOW,
NULL,
NULL,
&si,
&pi);
if (!fRet)
{
LPVOID lpMsgBuf;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL );
AfxMessageBox( (LPCTSTR)lpMsgBuf);
return FALSE;
}
四、使用如下封装好的函数(自己写的),尝试各种方法去启动可执行程序
CommandExecuter(const char *szAppName, const char *szCmd)
{
char szWorkPath[256] = {0};
char szCommand[256] = {0};
int j = 0;
//从配置文件中取参数
STARTUPINFO si = {0};
PROCESS_INFORMATION pi = {0};
si.cb = sizeof(si);
if ( szAppName != NULL && strlen(szAppName) > 0 )
{
memset( szWorkPath, 0, 256 );
GetSystemDirectory(szWorkPath, 256);
szWorkPath[3] = '\0';
strcat(szWorkPath, "Program Files\\");
strcat(szWorkPath, szAppName);
if(_access(szWorkPath, strlen(szWorkPath)) == -1)
{
strcpy(szWorkPath, szAppName);
}//if(_access(szWorkPath, strlen(szWorkPath)) == -1)
strcat(szWorkPath, " ");
strcat(szWorkPath, szCmd);
if ( CreateProcess( NULL,
(char *)szWorkPath,
NULL,
NULL,
FALSE,
0,
NULL,
NULL,
&si,
&pi ) )
{
CloseHandle( pi.hThread );
CloseHandle( pi.hProcess );
return;
}
if ( CreateProcess( szAppName,
(LPSTR)szCmd,
NULL,
NULL,
FALSE,
0,
NULL,
NULL,
&si,
&pi ) )
{
CloseHandle( pi.hThread );
CloseHandle( pi.hProcess );
return;
}
if ( (int)ShellExecute ( NULL,
NULL,
(LPCSTR)szWorkPath,
NULL,
NULL,
SW_SHOW ) > 32 )
{
// 启动成功了
return;
}
if ( (int)ShellExecute( NULL,
NULL,
szAppName,
(LPCSTR)szCmd,
NULL,
SW_SHOW ) > 32 )
{
// 启动成功了
return;
}
}//if ( szAppName != NULL && strlen(szAppName) > 0 )
else
{
if ( CreateProcess(NULL, (char *)szCmd, NULL, NULL, FALSE,
0, NULL, NULL, &si, &pi) )
{
CloseHandle( pi.hThread );
CloseHandle( pi.hProcess );
return;
}//if ( CreateProcess(NULL, (char *)szCmd, NULL, NULL,
FALSE, 0, NULL, NULL, &si, &pi) )
ShellExecute ( NULL, NULL, (LPCSTR)szCmd, NULL, NULL,
SW_SHOW );
}
}