您的位置:首页 > 其它

用VC6.0实现定时关机功能

2008-02-25 09:55 393 查看
                                                                   
                                                                  定时关机功能的实现
用SetTimer设定一个定时器,在定时器消息映射函数OnTimer中用CTime::GetCurrentTime得到当前系统时间,判断是否到达要求时间,如果到达则关机。 
 OSVERSIONINFO OsVersionInfo;   //包含操作系统版本信息的数据结构 
 OsVersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); 
 GetVersionEx(&OsVersionInfo);    //获取操作系统版本信息 
 if(OsVersionInfo.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) //对于WindowsNT系统
 { 
     HANDLE hToken; // 指向accesstoken的指针。 
     TOKEN_PRIVILEGES tkp;  //保存用户权限列表的数据结构。
      
     // Get a token for this process. 得到一个进程的accesstoken,并将它放入到hToken中。 
      
     if (!OpenProcessToken(GetCurrentProcess(),  
         TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))  
         AfxMessageBox("OpenProcessToken");  
          
     // Get the LUID for the shutdown privilege. 得到关机权限的LUID,并且放入到TOKEN_PRIVILEGES结构体的第一个列表项中。 
          
     LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,  
         &tkp.Privileges[0].Luid);  
      
     tkp.PrivilegeCount = 1;  // one privilege to set 将关机权限对应的LUID的对应属性改为可用  SE_PRIVILEGE_ENABLED;  
     tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;  
          
     // Get the shutdown privilege for this process. 调整进程的accesstoken,使它具有shutdown权限的可用属性。 
          
     AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,  
         (PTOKEN_PRIVILEGES)NULL, 0);  
      
     // Cannot test the return value of AdjustTokenPrivileges.  
      
     if (GetLastError() != ERROR_SUCCESS)  
         AfxMessageBox("AdjustTokenPrivileges");  
          
     // Shut down the system and force all applications to close.  
          
     if (!ExitWindowsEx(EWX_SHUTDOWN |EWX_POWEROFF, 0))  
            //EWX_REBOOT,EWX_LOGOFF      (uFlags) 
        //EWX_FORCE,EWX_FORCEIFHUNG  (Value) 
            AfxMessageBox("ExitWindowsEx");  
      
          
 } 
 else 
 { 
     //Windows98,调用ExitWindowsEx()函数重新启动计算机 
     ExitWindowsEx(EWX_SHUTDOWN |EWX_POWEROFF,0);  //可以改变第一个参数,实现注销用户、  
     //关机、关闭电源等操作 
          
          
 } 

下面是MSDN上面的相关资料。

1.什么是AccessToken

  AccessToken用来标识一个用户,其中包括用户的SID和用户所属组的SID,还包括这个用户和所属用户组的所拥有的权限列表。

当用户输入用户名和密码登陆到Windows之后,Windows会创建一个AcessToken,用来标识这个用户。在这个用户下创建的进程都将得到一份这个AccessToken的备份。当进程需要访问一个可以加密的对象(如文件,事件等)时,windows利用这个AccessToken来跟对象的SecurityDescriptor进行比较,以确认这个进程是否有权限来访问这个对象。(关于SID和SecurityDescriptor请参阅其他资料)

 

OSVERSIONINFO

TheOSVERSIONINFOdatastructurecontainsoperatingsystemversioninformation.Theinformationincludesmajorandminorversionnumbers,abuildnumber,aplatformidentifier,anddescriptivetextabouttheoperatingsystem.ThisstructureisusedwiththeGetVersionExfunction.用来保存操作系统版本的一个结构。

typedefstruct_OSVERSIONINFO{


    DWORDdwOSVersionInfoSize;


    DWORDdwMajorVersion;


    DWORDdwMinorVersion;


    DWORDdwBuildNumber;


    DWORDdwPlatformId;


    TCHARszCSDVersion[128];


}OSVERSIONINFO;


 

Members

dwOSVersionInfoSize
Specifiesthesize,inbytes,ofthisdatastructure.Setthismembertosizeof(OSVERSIONINFO)beforecallingtheGetVersionExfunction.
dwMajorVersion
Identifiesthemajorversionnumberoftheoperatingsystem.Forexample,forWindowsNTversion3.51,themajorversionnumberis3;andforWindowsNTversion4.0,themajorversionnumberis4.
dwMinorVersion
Identifiestheminorversionnumberoftheoperatingsystem.Forexample,forWindowsNTversion3.51,theminorversionnumberis51;andforWindowsNTversion4.0,theminorversionnumberis0.
dwBuildNumber
WindowsNT:Identifiesthebuildnumberoftheoperatingsystem.
Windows95:Identifiesthebuildnumberoftheoperatingsysteminthelow-orderword.Thehigh-orderwordcontainsthemajorandminorversionnumbers.
dwPlatformId
Identifiestheoperatingsystemplatform.Thismembercanbeoneofthefollowingvalues:
Value

Platform

VER_PLATFORM_WIN32s

Win32sonWindows3.1.

VER_PLATFORM_WIN32_WINDOWS

Win32onWindows95orWindows98.
ForWindows95,dwMinorVersioniszero.

ForWindows98,dwMinorVersionisgreaterthanzero.

VER_PLATFORM_WIN32_NT

Win32onWindowsNT.

 

 

 

szCSDVersion
WindowsNT:Containsanull-terminatedstring,suchas"ServicePack3",thatindicatesthelatestServicePackinstalledonthesystem.IfnoServicePackhasbeeninstalled,thestringisempty.
Windows95:Containsanull-terminatedstringthatprovidesarbitraryadditionalinformationabouttheoperatingsystem.
 

 

下面是MSDN上面对TOKEN_PRIVILEGES的解释:

TheTOKEN_PRIVILEGESstructurecontainsinformationaboutasetofprivilegesforanaccesstoken.这个结构用来包含一个accesstoken用户的权限列表。

typedefstruct_TOKEN_PRIVILEGES{//tp

   DWORDPrivilegeCount;

   LUID_AND_ATTRIBUTESPrivileges[ANYSIZE_ARRAY];

}TOKEN_PRIVILEGES;

下面是对成员的介绍:
Members

PrivilegeCount

SpecifiesthenumberofentriesinthePrivilegesarray.这个成员用来跟数组配套。

Privileges

SpecifiesanarrayofLUID_AND_ATTRIBUTESstructures.EachstructurecontainstheLUIDandattributesofaprivilege.Theattributesofaprivilegecanbeacombinationofthefollowingvalues:

这是一个LUID_AND_ATTRIBUTES结构的数组。每个结构包含一个LUID和权限的属性,属性由下列值组成:

Attribute

Description

SE_PRIVILEGE_ENABLED_BY_DEFAULT

 

Theprivilegeisenabledbydefault.

SE_PRIVILEGE_ENABLED

 

Theprivilegeisenabled.

SE_PRIVILEGE_USED_FOR_ACCESS

 

Theprivilegewasusedtogainaccesstoanobjectorservice.Thisflagisusedtoidentifytherelevantprivilegesinasetpassedbyaclientapplicationthatmaycontainunnecessaryprivileges.

 

下面是MSDN上对LUID的解释:

LUID

AnLUIDisa64-bitvalueguaranteedtobeuniqueonlyonthesystemonwhichitwasgenerated.Theuniquenessofalocallyuniqueidentifier(LUID)isguaranteedonlyuntilthesystemisrestarted.它是一个64位的值,一个LUID在系统里面是唯一的,直到系统重启。

AnLUIDisnotfordirectmanipulation.ApplicationsaretousefunctionsandstructurestomanipulateLUIDvalues.一个LUID是不能被直接操纵的,应用程序通过调用函数和结构来操纵它的值。

typedefLARGE_INTEGERLUID


 

 

 

 

OpenProcessToken

TheOpenProcessTokenfunctionopenstheaccesstokenassociatedwithaprocess.这个函数打开跟一个进程相关的accesstoken。

BOOLOpenProcessToken(


 HANDLEProcessHandle,//handletoprocess


 DWORDDesiredAccess//desiredaccesstoprocess


 PHANDLETokenHandle  //pointertohandleofopenaccesstoken


);



Parameters

ProcessHandle
Identifiestheprocesswhoseaccesstokenisopened.
DesiredAccess
Specifiesanaccessmaskthatspecifiestherequestedtypesofaccesstotheaccesstoken.Theserequestedaccesstypesarecomparedwiththetoken'sdiscretionaryaccess-controllist(ACL)todeterminewhichaccessesaregrantedordenied.Thefollowingaccessrightshavebeendefinedforaccesstokens.
Value

Meaning

TOKEN_ADJUST_DEFAULT

RequiredtochangethedefaultACL,primarygroup,orownerofanaccesstoken.

TOKEN_ADJUST_GROUPS

Requiredtochangethegroupsspecifiedinanaccesstoken.

TOKEN_ADJUST_PRIVILEGES

Requiredtochangetheprivilegesspecifiedinanaccesstoken.

TOKEN_ALL_ACCESS

CombinestheSTANDARD_RIGHTS_REQUIREDstandardaccessrightsandallindividualaccessrightsfortokens.

TOKEN_ASSIGN_PRIMARY

RequiredtoattachaprimarytokentoaprocessinadditiontotheSE_CREATE_TOKEN_NAMEprivilege.

TOKEN_DUPLICATE

Requiredtoduplicateanaccesstoken.

TOKEN_EXECUTE

CombinestheSTANDARD_RIGHTS_EXECUTEstandardaccessrightsandtheTOKEN_IMPERSONATEaccessright.

TOKEN_IMPERSONATE

Requiredtoattachanimpersonationaccesstokentoaprocess.

TOKEN_QUERY

Requiredtoquerythecontentsofanaccesstoken.

TOKEN_QUERY_SOURCE

Requiredtoquerythesourceofanaccesstoken.

TOKEN_READ

CombinestheSTANDARD_RIGHTS_READstandardaccessrightsandtheTOKEN_QUERYaccessright.

TOKEN_WRITE

CombinestheSTANDARD_RIGHTS_WRITEstandardaccessrightsandtheTOKEN_ADJUST_PRIVILEGES,TOKEN_ADJUST_GROUPS,andTOKEN_ADJUST_DEFAULTaccessrights.

 

TokenHandle
Pointertoahandleidentifyingthenewly-openedaccesstokenwhenthefunctionreturns.

ReturnValues

Ifthefunctionsucceeds,thereturnvalueisnonzero.如果函数调用成功,那么返回非零值

Ifthefunctionfails,thereturnvalueiszero.Togetextendederrorinformation,callGetLastError.如果调用失败,返回0.

 

LookupPrivilegeValue

TheLookupPrivilegeValuefunctionretrievesthelocallyuniqueidentifier(LUID)usedonaspecifiedsystemtolocallyrepresentthespecifiedprivilegename.这个函数用来重新得到在当前系统中,权限名字所对应的LUID号。

BOOLLookupPrivilegeValue(


 LPCTSTRlpSystemName,


                  //addressofstringspecifyingthesystem


 LPCTSTRlpName//addressofstringspecifyingtheprivilege


 PLUIDlpLuid    //addressoflocallyuniqueidentifier


);



Parameters

lpSystemName
Pointertoanull-terminatedstringspecifyingthenameofthesystemonwhichtheprivilegenameislookedup.Ifanullstringisspecified,thefunctionattemptstofindtheprivilegenameonthelocalsystem.指定要在哪个系统中查找权限所对应的LUID,如果为NULL,则表示默认为当前系统。
lpName
Pointertoanull-terminatedstringthatspecifiesthenameoftheprivilege,asdefinedintheWINNT.Hheaderfile.Forexample,thisparametercouldspecifytheconstantSE_SECURITY_NAME,oritscorrespondingstring,"SeSecurityPrivilege".指定所要查询的权限的名字。
lpLuid
PointertoavariablethatreceivesthelocallyuniqueidentifierbywhichtheprivilegeisknownonthesystemspecifiedbythelpSystemNameparameter.指定用来保存LUID的结构的指针。

ReturnValues

Ifthefunctionsucceeds,thereturnvalueisnonzero.

Ifthefunctionfails,thereturnvalueiszero.Togetextendederrorinformation,callGetLastError.

 

AdjustTokenPrivileges

TheAdjustTokenPrivilegesfunctionenablesordisablesprivilegesinthespecifiedaccesstoken.EnablingordisablingprivilegesinanaccesstokenrequiresTOKEN_ADJUST_PRIVILEGESaccess.这个函数用来使某个权限能用或者禁止某个权限。要求第一个参数要有TOKEN_ADJUST_PRIVILEGES。

BOOLAdjustTokenPrivileges(


 HANDLETokenHandle//handletotokenthatcontainsprivileges


 BOOLDisableAllPrivileges,


                      //flagfordisablingallprivileges


 PTOKEN_PRIVILEGESNewState,


                      //pointertonewprivilegeinformation


 DWORDBufferLength//size,inbytes,ofthePreviousStatebuffer


 PTOKEN_PRIVILEGESPreviousState,


                      //receivesoriginalstateofchanged


                       //privileges


 PDWORDReturnLength //receivesrequiredsizeofthe


                       //PreviousStatebuffer


);



Parameters

TokenHandle
Identifiestheaccesstokenthatcontainstheprivilegestobemodified.ThehandlemusthaveTOKEN_ADJUST_PRIVILEGESaccesstothetoken.IfthePreviousStateparameterisnotNULL,thehandlemustalsohaveTOKEN_QUERYaccess.
DisableAllPrivileges
Specifieswhetherthefunctiondisablesallofthetoken'sprivileges.IfthisvalueisTRUE,thefunctiondisablesallprivilegesandignorestheNewStateparameter.IfitisFALSE,thefunctionmodifiesprivilegesbasedontheinformationpointedtobytheNewStateparameter.
NewState
PointertoaTOKEN_PRIVILEGESstructurethatspecifiesanarrayofprivilegesandtheirattributes.IftheDisableAllPrivilegesparameterisFALSE,AdjustTokenPrivilegesenablesordisablestheseprivilegesforthetoken.IfyousettheSE_PRIVILEGE_ENABLEDattributeforaprivilege,thefunctionenablesthatprivilege;otherwise,itdisablestheprivilege.
IfDisableAllPrivilegesisTRUE,thefunctionignoresthisparameter.
BufferLength
Specifiesthesize,inbytes,ofthebufferpointedtobythePreviousStateparameter.ThisparametercanbeNULLifthePreviousStateparameterisNULL.
PreviousState
PointertoabufferthatthefunctionfillswithaTOKEN_PRIVILEGESstructurecontainingthepreviousstateofanyprivilegesthefunctionmodifies.ThisparametercanbeNULL.
Ifyouspecifyabufferthatistoosmalltoreceivethecompletelistofmodifiedprivileges,thefunctionfailsanddoesnotadjustanyprivileges.Inthiscase,thefunctionsetsthevariablepointedtobytheReturnLengthparametertothenumberofbytesrequiredtoholdthecompletelistofmodifiedprivileges.
ReturnLength
Pointertoavariablethatreceivestherequiredsize,inbytes,ofthebufferpointedtobythePreviousStateparameter.ThisparametercanbeNULLifPreviousStateisNULL.

ReturnValues

Ifthefunctionsucceeds,thereturnvalueisnonzero.Todeterminewhetherthefunctionadjustedallofthespecifiedprivileges,callGetLastError,whichreturnsoneofthefollowingvalueswhenthefunctionsucceeds:

Value

Description

ERROR_SUCCESS

Thefunctionadjustedallspecifiedprivileges.

ERROR_NOT_ALL_ASSIGNED

ThetokendoesnothaveoneormoreoftheprivilegesspecifiedintheNewStateparameter.Thefunctionmaysucceedwiththiserrorvalueevenifnoprivilegeswereadjusted.ThePreviousStateparameterindicatestheprivilegesthatwereadjusted.

 

Ifthefunctionfails,thereturnvalueiszero.Togetextendederrorinformation,callGetLastError.

Remarks

TheAdjustTokenPrivilegesfunctioncannotaddnewprivilegestotheaccesstoken.Itcanonlyenableordisablethetoken'sexistingprivileges.Todeterminethetoken'sprivileges,calltheGetTokenInformationfunction.

NotethattheNewStateparametercanspecifyprivilegesthatthetokendoesnothave,withoutcausingthefunctiontofail.Inthiscase,thefunctionadjuststheprivilegesthatthetokendoeshave,ignorestheotherprivileges,andreturnssuccess.CalltheGetLastErrorfunctiontodeterminewhetherthefunctionadjustedallofthespecifiedprivileges.ThePreviousStateparameterindicatestheprivilegesthatwereadjusted.

ThePreviousStateparameterretrievesaTOKEN_PRIVILEGESstructurecontainingthetheoriginalstateoftheadjustedprivileges.Torestoretheoriginalstate,passthePreviousStatepointerastheNewStateparameterinasubsequentcalltotheAdjustTokenPrivilegesfunction

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息