Is there an API call to prompt user for UAC elevation?

前端 未结 3 1606
猫巷女王i
猫巷女王i 2021-01-06 03:02

My app needs to write to a file in \\ProgramData that could be protected. This only happens once after installation.

Is there an API function that would take ACL inf

3条回答
  •  一生所求
    2021-01-06 03:20

    Thanks to @Remy for the ShellExecuteEx suggestion, here are the sordid details. Note the use of 'cmd' and the double-command, so the user only has to reply once. Also, [1] must wait for process completion otherwise you could find yourself creating the file before it was deleted, and [2] don't wait for the process if it failed.

    // delete file with Admin privilege
    // 'file_name' is path of file to be deleted
    SHELLEXECUTEINFO shex;
    char param[512];
    char *cmd = "/C \"attrib -H \"%s\" && del /F /Q \"%s\"\""; // double command
    
    _snprintf(param, sizeof(param), cmd, file_name, file_name);
    ZeroMemory(&shex, sizeof(shex));
    shex.cbSize = sizeof(shex);
    shex.lpVerb = "runas";  // runas, open
    shex.lpFile = "cmd";    // not 'del'
    shex.lpParameters = param;
    shex.nShow = SW_HIDE;
    shex.fMask = SEE_MASK_NOCLOSEPROCESS;
    BOOL retshx = ShellExecuteEx(&shex);
    // wait otherwise could return before completed
    if(retshx)
    {   time_t st = clock();
        DWORD exitCode;
        do
        {   if(!GetExitCodeProcess(shex.hProcess, &exitCode))
                break;
            if(clock() - st > CLOCKS_PER_SEC * 5)       // max 5 seconds
                break;
        } while(exitCode != STATUS_WAIT_0); // STILL_ACTIVE
        CloseHandle(shex.hProcess);
    }
    

提交回复
热议问题