Vista UAC, Access Elevation and .Net

后端 未结 6 919
死守一世寂寞
死守一世寂寞 2020-12-10 18:18

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

6条回答
  •  一生所求
    2020-12-10 18:47

    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);
    }
    

提交回复
热议问题