2012年7月5日星期四

IsUserAnAdmin.Cpp


/*
看到一些判断是不是管理员的小代码,没有细看。方法很多。
原来一个函数就能实现,关键在于知识,知识面,技术?
下面这两个是取自msdn,觉得最正宗的还是用微软的。
再详细的注释下:
是判断当前用户是不是管理员的组的成员,并不一定是administrator用户.
在win 7下非administrator的组的用户,以administrator组的成员的权限运行,需要输入密码的情况,别当另论。
*/
#include <Windows.h>
#include <Shlobj.h>

#pragma comment (lib,"Shell32.lib")

BOOL IsUserAdmin(VOID)
/*++ 
Routine Description: This routine returns TRUE if the caller's
process is a member of the Administrators local group. Caller is NOT
expected to be impersonating anyone and is expected to be able to
open its own process and process token. 
Arguments: None. 
Return Value: 
TRUE - Caller has Administrators local group. 
FALSE - Caller does not have Administrators local group. --
*/ 
{
    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);
}

int main(int argc, char* argv[])
{
    bool b =  IsUserAnAdmin();
    if (b)
    {
        MessageBox(0,L"IsUserAnAdmin",0,0);
    }
    else 
    {
        MessageBox(0,L"not_IsUserAnAdmin",0,0);
    }

    b = IsUserAdmin();
    if (b)
    {
        MessageBox(0,L"IsUserAdmin",0,0);
    }
    else 
    {
        MessageBox(0,L"not_IsUserAdmin",0,0);
    }

    return 0;
}

没有评论:

发表评论