My application does not always require "admin" privileges and most of the time would run as the current user. Is there any way, I can escalate privs by throwing up a UAC at runtime after my program is already running? This will only happen as and when I need privs. Rather than having to start with high privs.
I know the "runas" technique, manifest file etc. but all these are before the process is created and not at runtime, on-demand
Congratulations, that's exactly how UAC is designed to work, and something most application developers are either too lazy or too scared to ever contemplate looking at :)
In a nutshell, you put the code that needs elevation in a separate COM object (that lives in a DLL), and then you create an elevated instance of it using the method described here.
HRESULT CoCreateInstanceAsAdmin(HWND hwnd, REFCLSID rclsid, REFIID riid, __out void ** ppv)
{
BIND_OPTS3 bo;
WCHAR wszCLSID[50];
WCHAR wszMonikerName[300];
StringFromGUID2(rclsid, wszCLSID, sizeof(wszCLSID)/sizeof(wszCLSID[0]));
HRESULT hr = StringCchPrintf(wszMonikerName, sizeof(wszMonikerName)/sizeof(wszMonikerName[0]),\
L"Elevation:Administrator!new:%s", wszCLSID);
if (FAILED(hr))
return hr;
memset(&bo, 0, sizeof(bo));
bo.cbStruct = sizeof(bo);
bo.hwnd = hwnd;
bo.dwClassContext = CLSCTX_LOCAL_SERVER;
return CoGetObject(wszMonikerName, &bo, riid, ppv);
}
The key is the Elevation:Administrator!new:
prefix to the moniker name. This causes the elevation prompt to be triggered, and the resulting COM object will be created with an elevated token.