如何在 win xp 下在运行时提升我的进程 [英] How can i elevate my process at runtime under win xp

查看:51
本文介绍了如何在 win xp 下在运行时提升我的进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序需要在运行时执行一些特权操作.例如,当用户第一次运行我的应用程序时,我必须创建并格式化一个虚拟目录.我使用未记录的 api formatex 来完成格式化工作,但 formatex 需要管理员权限.如果操作系统是 vista 或更高版本,我可以使用COM Elevation Moniker"提示 UAC 对话框并且它工作正常.但是在xp上,这种技术不适合,所以我使用了impersonate方法.如果应用程序以受限用户身份运行,我会像这样进行格式化:

My app needs to do some privileged operations at runtime. For example,when the user is first time to run my app, i have to create and format a virtual dirve. I use the undocumented api formatex to do the fomating job, but formatex need administrator privileges. If OS is vista or later, i can prompt UAC dialog with 'COM Elevation Moniker' and it works fine. But on xp, this technique is not suitable, so i use the impersonate method. if app is run as limited user, i do formating like this:

CredUIPromptForCredentials() -> prompt to get administrator credentials
LogonUser()
ImpersonateLoggedOnUser()
formatex()
RevertToSelf()

formatex 仍然失败...当然,以管理员身份运行我的应用程序是可行的,但这并不好,我的应用程序是按用户安装的,而不是按机器安装的,这应该在当前用户上下文下工作,即使用户是受限用户.

formatex still fail... Of course, run my app as administrator will works, but it is not good, my app is installed as per user, not per machine, which should work under current user context, even if the user is a limited user.

如何在运行时正确提升我的应用程序以完成格式化工作?有人帮忙吗?

How can i correctly elevate my app at runtime to do the formating job? Any one help?

推荐答案

一个可能的解决方案是使用提升的权限和一些命令行参数重新执行应用程序,这些参数将指示执行实际格式化.

A possible solution is to re-execute the application with elevated privileges and some command line parameter which will instruct to perform actual formatting.

示例代码:

if (!IsUserAdmin()) {
     RunAsAdmin(hwnd, exeName, "--do-format");
} else {
     DoFormat();
}
...

BOOL RunAsAdmin(HWND hWnd, LPCTSTR lpFile, LPCTSTR lpParameters)
{
    SHELLEXECUTEINFO sei;
    ZeroMemory(&sei, sizeof(sei));

    sei.cbSize          = sizeof(SHELLEXECUTEINFOW);
    sei.hwnd            = hWnd;
    sei.fMask           = SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
    sei.lpVerb          = _TEXT("runas");
    sei.lpFile          = lpFile;
    sei.lpParameters    = lpParameters;
    sei.nShow           = SW_SHOWNORMAL;

    if (!ShellExecuteEx(&sei)) {
            return FALSE;
    }
    return TRUE;
}

BOOL IsUserAdmin(VOID)
{
    BOOL b;
    SID_IDENTIFIER_AUTHORITY NtAuthority = { SECURITY_NT_AUTHORITY };
    PSID AdministratorsGroup;
    b = AllocateAndInitializeSid(
            &NtAuthority,
            2,
            SECURITY_BUILTIN_DOMAIN_RID,
            DOMAIN_ALIAS_RID_ADMINS,
            0, 0, 0, 0, 0, 0,
            &AdministratorsGroup);
    if (b) {
            if (!CheckTokenMembership( NULL, AdministratorsGroup, &b)) {
                    b = FALSE;
            }
            FreeSid(AdministratorsGroup);
    }

    return b;
}

这篇关于如何在 win xp 下在运行时提升我的进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆