Requesting administrator privileges at run time

You can elevate a process only during its creation. When a process already runs, there's no way to change its security token: it either runs elevated or not.

If your application needs to perform an administrative task, and it usually runs non-elevated, you have to create another .exe which will request elevation with its manifest. To start a process elevated, you have to use ShellExecute or ShellExecuteEx function. From your main process you will need a way to pass the commands to that new process that will run elevated.


For more information about UAC, read Designing UAC Applications for Windows Vista series.


Not quite, but you can do the opposite—you can drop privileges if you already have them. So, you can have your program start out running as an Administrator, using one of the methods listed by Kate Gregory. Then, drop your unneeded privileges; see Dropping privileges in C++ on Windows for how to do that.


If you want the application to always elevate, you can give it a manifest, either by building one in (not compiling technically) or by putting an external manifest in the same folder as the exe. If you want to decide, as a person, to run it elevated, you right click the exe or short cut and choose Run As Administrator. If you are launching it from code, then as @vcsjones comments, you use the runas verb when you launch that process. For example:

ShellExecute( NULL, 
    "runas",  
    "c:\\windows\\notepad.exe",  
    " c:\\temp\\report.txt",     
    NULL,                        // default dir 
    SW_SHOWNORMAL  
); 

Tags:

Windows

C++

Uac