C++启动其它exe程序的代码

来源:互联网 发布:sublime windows 编辑:程序博客网 时间:2024/05/18 00:09

先取到所要启动exe的绝对路径,比如: C:\Test\update.exe
也要得到exe所存在的目录路径,比如: C:\Test

1.先用Qt实现

QString path = "C:\\Test\\update.exe";QString runPath = "C:\\Test";QProcess *process = new QProcess;process->setWorkingDirectory(runPath);process->start("\"" + path + "\"");

但如果update.exe是有管理员权限的程序,那么上面的代码将无法运行起update.exe
有管理员权限的exe,就要用以下的代码。


2.用ShellExecuteEx

QString path = "C:\\Test\\update.exe";QString runPath = "C:\\Test";BPtr<char> updateFilePath = (char*)path.toStdString().c_str();BPtr<char> updateDirPath = (char*)runPath.toStdString().c_str();BPtr<wchar_t> wUpdateFilePath;BPtr<wchar_t> wUpdateDirPath;size_t size = os_utf8_to_wcs_ptr(updateFilePath, 0, &wUpdateFilePath);size_t size1 = os_utf8_to_wcs_ptr(updateDirPath, 0, &wUpdateDirPath);if (!size || !size1)    throw string("Could not convert updateFilePath to wide");/* note, can't use CreateProcess to launch as admin. */SHELLEXECUTEINFO execInfo = {};execInfo.cbSize = sizeof(execInfo);execInfo.lpFile = wUpdateFilePath;execInfo.lpParameters = L"";execInfo.lpDirectory = wUpdateDirPath;execInfo.nShow       = SW_SHOWNORMAL;if (!ShellExecuteEx(&execInfo)) {    throw string("run exe fail");}

上面的os_utf8_to_wcs_ptr 是转宽字符串的。