I'm trying to find out if there is any way to elevate a specific function within an application. For example, I have an app with system and user settings that are stored in the registry, I only need elevation for when the system settings need to be changed.
Unfortunately all of the info I've come across talks about only starting a new process with elevated privileges.
It is impossible to elevate just one function or any other part of a single process, because the elevation level is a per-process attribute. Just like with pregnancy, your process can either be elevated or not. If you need some part of your code to be running elevated, you must start a separate process.
However, if you can implement your function as a COM object, you can run it elevated indirectly, by creating an elevated COM object, like this:
HRESULT
CreateElevatedComObject (HWND hwnd, REFGUID guid, REFIID iid, void **ppv)
{
WCHAR monikerName[1024];
WCHAR clsid[1024];
BIND_OPTS3 bo;
StringFromGUID2 (guid, clsid, sizeof (clsid) / 2);
swprintf_s (monikerName, sizeof (monikerName) / 2, L"Elevation:Administrator!new:%s", clsid);
memset (&bo, 0, sizeof (bo));
bo.cbStruct = sizeof (bo);
bo.hwnd = hwnd;
bo.dwClassContext = CLSCTX_LOCAL_SERVER;
// Prevent the GUI from being half-rendered when the UAC prompt "freezes" it
MSG paintMsg;
int MsgCounter = 5000; // Avoid endless processing of paint messages
while (PeekMessage (&paintMsg, hwnd, 0, 0, PM_REMOVE | PM_QS_PAINT) != 0 && --MsgCounter > 0)
{
DispatchMessage (&paintMsg);
}
return CoGetObject (monikerName, &bo, iid, ppv);
}
The best article I have seen is this one:
http://www.codeproject.com/KB/vista-security/UAC__The_Definitive_Guide.aspx
It explains down to the nitty gritty of whats going on behind the scenes when existing microsoft applications are bringing up the UAC prompt, and a bit of how to do it yourself, or at least you will know what your up against to make it work...
(note the examples he shows are managed c++)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With