如一个程序A.exe以普通权限运行,但需要以管理员权限调起B.exe,本文主要讲述两种办法,亲测可用。
1.第一种方法
#include <stdio.h>
#include<windows.h>
#include<tchar.h>
int _tmain(int argc, _TCHAR* argv[])
{
SHELLEXECUTEINFO sei = { sizeof(SHELLEXECUTEINFO) };
sei.lpVerb = TEXT("runas");
sei.lpFile = TEXT("cmd.exe");//add application which you want to run as administrator here
sei.nShow = SW_SHOWNORMAL;//without this,the windows will be hiden
if (!ShellExecuteEx(&sei)){
DWORD dwStatus = GetLastError();
if (dwStatus == ERROR_CANCELLED){
printf("提升权限时被用户拒绝\n");
}
else if (dwStatus == ERROR_FILE_NOT_FOUND){
printf("所要执行的文件没有找到\n");
}
}
return 0;
}
----------------------------------------------------------------------------------------------------------------------------------
2.第二种方法
int _tmain(int argc, _TCHAR* argv[])
{
qDebug()<<"updateBtn_clicked";
QString exePath = "cmd.exe";
WCHAR exePathArray[1024] = {0};
exePath.toWCharArray(exePathArray);
QString command = " -Updater";
WCHAR commandArr[1024] = {0};
command.toWCharArray(commandArr);
HINSTANCE hNewExe = ShellExecute(NULL, L"runas",exePathArray,commandArr,NULL,SW_SHOWMAXIMIZED);
int nReturn = (int)hNewExe;
}