MFC在windows7下用shellexcuteex动态提权

char szFileName[MAX_PATH];
ZeroMemory(szFileName,MAX_PATH);
::GetModuleFileName(NULL, szFileName, MAX_PATH);
SHELLEXECUTEINFO ShExecInfo = { 0 } ;
ShExecInfo.cbSize = sizeof( SHELLEXECUTEINFO ) ;
ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS ;
ShExecInfo.hwnd = NULL;
ShExecInfo.lpVerb = “runas”;
ShExecInfo.lpFile = szFileName;
ShExecInfo.lpParameters = “autostart”;
ShExecInfo.nShow = SW_HIDE;
ShExecInfo.hInstApp = NULL ;
ShellExecuteEx(&ShExecInfo);

最近在写一个程序,需要开机自启动,但是修改注册表强加自启动会触发UAC,如果在程序里添加24号资源会使得每次启动都会触发UAC(就是exe图标里有个小盾牌),但是这种程序win7里面开机时发现程序有小盾牌的都不会启动。so百度了一下,用了动态触发UAC提权的方式解决这个问题。

1.在设置开机自启动时,强制触发uac并启动本exe的另外一个进程,这样另外一个进程就是以高权限运行了

char szFileName[MAX_PATH];

ZeroMemory(szFileName,MAX_PATH);

::GetModuleFileName(NULL, szFileName, MAX_PATH);

SHELLEXECUTEINFO ShExecInfo = { 0 } ;

ShExecInfo.cbSize = sizeof( SHELLEXECUTEINFO ) ;

ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS ;

ShExecInfo.hwnd = NULL;

ShExecInfo.lpVerb = “runas”;//这行最主要

ShExecInfo.lpFile = szFileName;

ShExecInfo.lpParameters = “autostart”;

ShExecInfo.nShow = SW_HIDE;

ShExecInfo.hInstApp = NULL ;

ShellExecuteEx(&ShExecInfo);

2.在cmyapp的InitInstance里获取命令行参数,如果是autostart的则改注册表并exit,注意,这段代码得添加在dlg的domodal前面。

//下面是以特殊方式启动并修改自启动的

std::string strCmd = this->m_lpCmdLine;

if (strCmd.find(“autostart”)!=std::string::npos)

{

CString   str; //添加注册表路径

//WCHAR*     CurrentPath=(WCHAR*)malloc(sizeof(char)*100);//程序当前路径

char*     CurrentPath= new char[100];//程序当前路径

HKEY   hRegKey;   //注册key

BOOL   bResult;   //打开注册表返回值

str=_T(“Software\\Microsoft\\Windows\\CurrentVersion\\Run”);//注册表

GetModuleFileName(NULL,CurrentPath,MAX_PATH); //获得运用程序路径

if(bResult=RegOpenKey(HKEY_LOCAL_MACHINE,   str,   &hRegKey)   !=   ERROR_SUCCESS)//打开注册表

{

//free(CurrentPath); //打开不成功就释放内存并返回

delete[] CurrentPath;

return FALSE;

}

if(bResult=::RegSetValueEx(hRegKey,_T(“StarBySelf”),0,REG_SZ,

(const   unsigned   char   *)CurrentPath,

MAX_PATH)!=   ERROR_SUCCESS)   //打开成功写信息到注册表

{   //写入失败

RegCloseKey(hRegKey);   //关闭注册表key

//   free(CurrentPath);   //释放内存资源

delete[] CurrentPath;

return FALSE;   //返回

}

//成功后执行释放内存

RegCloseKey(hRegKey);

// free(CurrentPath);

delete[] CurrentPath;

return FALSE;

}

Leave a Reply