windows下执行exe或bat等程序的四种方法:
#include<iostream>
#include<windows.h>
using namespace std;
wstring string2wstring(string str)
{
wstring result = L"";
LPCSTR temp = str.c_str();
int len = ::MultiByteToWideChar(CP_ACP, 0, temp, -1,NULL, 0);
LPWSTR lwStr = (LPWSTR)new char[len * 2 + 4];
::MultiByteToWideChar(CP_ACP, 0, temp, -1, lwStr, len);
result = lwStr;
delete[] lwStr;
return result;
}
//方法1
void test01()
{
string App1 = "start.bat";
string Path = "E:/AEHF-v1.0";
SetCurrentDirectoryA(Path.c_str());
WinExec(App1.c_str(),SW_HIDE);
}
//方法2
void test02()
{
string App = "start.bat";
std::wstring App1 = string2wstring(App);
string Path = "E:/AEHF-v1.0";
PROCESS_INFORMATION pi;
STARTUPINFO si;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
SetCurrentDirectoryA(Path.c_str());
if (CreateProcess((App1.c_str()),NULL,NULL,NULL,FALSE,NULL,NULL,NULL,&si,&pi))
{
WaitForSingleObject(pi.hProcess,INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
}
//方法3
void test03()
{
//打印当前程序的执行路径
system("chdir");
string App1 = "start.bat";
string Path = "E:/AEHF-v1.0";
SetCurrentDirectoryA(Path.c_str());
system(App1.c_str());
}
//方法4
void test04()
{
string App = "start.bat";
std::wstring App1 = string2wstring(App);
string Path = "E:/AEHF-v1.0";
SetCurrentDirectoryA(Path.c_str());
HINSTANCE hnewExe = ::ShellExecute(NULL,L"",App1.c_str(),NULL,NULL,SW_SHOWMINIMIZED); //异步执行
if ((DWORD)hnewExe<=32)
{
cout << "失败!" << (DWORD)hnewExe << endl;
}
else
{
cout << "成功!" << endl;
}
}