请问怎么在NT下用Delphi实现自动关机?我试过ExitWindowsEx不好使,只在98下好使。

解决方案 »

  1.   

    需要设置权限
    function SetPrivilege(sPrivilegeName:string;bEnabled:boolean):boolean;
    var
      TP,TPPre:TTokenPrivileges;
      Token:THandle;
      dwLength:DWORD;
    begin
      result := false;
      OpenProcessToken(GetCurrentProcess,TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY,Token);
      try
      TP.PrivilegeCount := 1;
      if LookupPrivilegeValue(nil,PChar(sPrivilegeName),TP.Privileges[0].LUID) then
      begin
        if bEnabled then
          TP.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED
        else
          TP.Privileges[0].Attributes := 0;
        dwLength := 0;
        Result := AdjustTokenPrivileges(Token,false,TP,sizeof(TPPre),TPPre,dwLength);
      end;
      finally
        CloseHandle(Token);
      end;
    end;
    调用:
        SetPrivilege('SeShutdownPrivilege',true);
        ExitWindowsEx(EWX_SHUTDOWN or EWX_FORCE or EWX_POWEROFF,0);
      

  2.   

    要写这么多吗?有一点不同在Win9x下关机是用EWX_SHUTDOWN,而NT/2K/XP下关机是用EWX_POWEROFFprocedure TForm1.FormCreate(Sender: TObject);
    var     htmp,hToken:Thandle;
        tkp:TOKEN_PRIVILEGES;
        tkpOld:TOKEN_PRIVILEGES;
    begin
          OpenProcessToken(GetCurrentProcess,TOKEN_ADJUST_PRIVILEGES Or TOKEN_QUERY,hToken);
          LookupPrivilegeValue(nil, 'SeShutdownPrivilege',tkp.Privileges[0].Luid);
          tkp.PrivilegeCount:=1;
          tkp.Privileges[0].Attributes:= SE_PRIVILEGE_ENABLED;
          AdjustTokenPrivileges(hToken, false, tkp, sizeof(tkpOld), tkpOld, htmp);
         ExitwindowsEx(EWX_POWEROFF,0);
    end;