如何运行需要管理员权限的应用程序,而不需要管理员权限

Sam*_*uel 24 c++ winapi uac createprocess shellexecute

我已经坚持了几个小时,直到我终于成功了.已有链接指向我正确的方向:

但我认为这个问题的简单概述可以帮助某人:).

Sam*_*uel 30

真正的问题:(来自维基百科:http://en.wikipedia.org/wiki/User_Account_Control)

在其清单中标记为"requireAdministrator"的可执行文件无法使用CreateProcess()从非提升的进程启动.而是返回ERROR_ELEVATION_REQUIRED.必须使用ShellExecute()或ShellExecuteEx().

(BTW,ERROR_ELEVATION_REQUIRED错误== 740)

解决方案:(同一网站)

在本机Win32应用程序中,可以将相同的"runas"动词添加到ShellExecute()或ShellExecuteEx()调用中.

ShellExecute(hwnd, "runas", "C:\\Windows\\Notepad.exe", 0, 0, SW_SHOWNORMAL);

这可能也有帮助:(来源:http://mark.koli.ch/2009/12/uac-prompt-from-java-createprocess-error740-the-requested-operation-requires-elevation.html)

2 - 基本UAC流程

好的,所以在深入研究之前,我认为解释UAC感知应用程序的基本流程以及所有内容如何组合起来可能会有所帮助.通常,您的应用程序以非特权用户身份运行.但是,有时它需要成为管理员(做任何事情).所以,这是伪代码中的基本思想:

int main (int argc, char **argv) {

  HRESULT operation = tryToDoSomethingPrivileged();

  if (operation == ACCESS_DENIED && !alreadyElevated) {

    // Spawn a copy of ourselves, via ShellExecuteEx().
    // The "runas" verb is important because that's what
    // internally triggers Windows to open up a UAC prompt.
    HANDLE child = ShellExecuteEx(argc, argv, "runas");

    if (child) {
      // User accepted UAC prompt (gave permission).
      // The unprivileged parent should wait for
      // the privileged child to finish.
      WaitForSingleObject(child, INFINITE);
      CloseHandle(pid);
    }
    else {
      // User rejected UAC prompt.
      return FAILURE;
    }

    return SUCCESS;

  }  

  return SUCCESS;

}
Run Code Online (Sandbox Code Playgroud)

最后,我就是这样做的:

if(0 == CreateProcess(argv[2], params, NULL, NULL, false, 0, NULL, NULL, &si, &pi)) {
        //runas word is a hack to require UAC elevation
        ShellExecute(NULL, "runas", argv[2], params, NULL, SW_SHOWNORMAL);
}
Run Code Online (Sandbox Code Playgroud)

只是出于完整性的考虑 - MSDN链接到ShellExecute和CreateProcess:

http://msdn.microsoft.com/en-us/library/bb762153%28v=vs.85%29.aspx

http://msdn.microsoft.com/en-us/library/ms682425%28VS.85%29.aspx

  • ShellExecuteEx接受一个参数,一个指向SHELLEXECUTEINFO的指针.http://msdn.microsoft.com/en-us/library/windows/desktop/bb762154(v=vs.85).aspx (3认同)