我试图找出是否有任何方法可以提升应用程序中的特定功能。例如,我有一个应用程序,其系统和用户设置存储在注册表中,我只需要在需要更改系统设置时进行提升。
不幸的是,我遇到的所有信息都在谈论只启动具有提升权限的新进程。
不可能只提升一个功能或单个流程的任何其他部分,因为提升级别是每个流程的属性。就像怀孕一样,您的过程可以升高也可以不升高。如果您需要运行提升的代码的某些部分,则必须启动一个单独的进程。
但是,如果您可以将函数实现为 COM 对象,则可以通过创建提升的 COM 对象来间接提升它,如下所示:
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);
}
我看过的最好的文章是这篇:
http://www.codeproject.com/KB/vista-security/UAC__The_Definitive_Guide.aspx
它解释了当现有的 Microsoft 应用程序启动 UAC 提示时幕后发生的事情的本质,以及一些如何自己做的事情,或者至少你会知道你要面对什么来使它工作。 ..
(注意他展示的示例是托管 c++)
The Windows SDK "Cross Technology Samples" have a "UACDemo" application which shows examples of a C# Windows Forms application which launches an administrator process to perform a task which requires elevation (i.e. writing to %programfiles%
).
This is a great starting point for writing your own functionality. I've extended this sample to use .Net Remoting and IPC to call between my normal user process and my elevated process which allows me to keep the elevation executable generic and implement application-specific code within the application.
您真正需要做的是将您的设置存储在 Application Data 文件夹中。
I think Aydsman is on the right track here. With the addition of Named Pipes support to .NET 3.5, you have a decent IPC mechanism for communicating with an elevated child process.