Home Index

Shutting down a Windows NT/2000
 
Date: February 01 2001
Subject: Online Programmer Ezine, Volume 2, No.2
Article: Shutting down a Windows NT/2000

Shutting down windows 98 is an easy task. You can use a 
one-line code:

ExitWindowsEx(EWX_SHUTDOWN,0xffff);

But if you try it on a Windows NT or 2000 you will see that 
shut down is not successful. This is because your program 
does not have the permission to shut down your server.

This article will show you how to get the permission needed 
to shut down the server.

We describe program step by step. 

1- We need to know if this is a Windows NT or 2000. If this
is a win98 we will ignore steps needed to get the permission
for shut down because windows 98 does not need so. 
IsWindowsNT() function is written for this purpose.

2- We need another function that adjusts permissions so that
our program can shut down server. We have called this 
function AdjToken().

3- After we adjusted permissions we can call ExitWindowEx() 
function to shut down server.

4- Above steps is implemented inside ShutIt function so this
function will shutdown server regardless of windows type.

You can download source codes from our site. 

http://op.htmsoft.com

And now the source code:


int ShutIt()
{
if (IsWindowsNT())
{
AdjToken();
if (GetLastError()!=0)
Application->
MessageBox("Post Adjust Token error","Error",MB_OK);
}

ExitWindowsEx(EWX_SHUTDOWN,0xffff);
return 0;
}


BOOL IsWindowsNT()
{
DWORD dwVersion = GetVersion();

if ( dwVersion < 0x80000000)
return TRUE;
else
return FALSE;
}



void AdjToken()
{
HANDLE hToken;
LUID tmpLuid;

HANDLE handleProcess=GetCurrentProcess();

if(!OpenProcessToken(handleProcess,TOKEN_ADJUST_PRIVILEGES
|TOKEN_QUERY,&hToken))
Application->
MessageBox("Open Process Token Error","Error",MB_OK);

if(!LookupPrivilegeValue(0,"SeShutdownPrivilege", &tmpLuid))
Application->
MessageBox("Lookup PrivilegeValue error","Error",MB_OK);

TOKEN_PRIVILEGES NewState;
LUID_AND_ATTRIBUTES luidattr;

NewState.PrivilegeCount = 1;
luidattr.Luid=tmpLuid;
luidattr.Attributes=SE_PRIVILEGE_ENABLED;
NewState.Privileges[0]=luidattr;

AdjustTokenPrivileges(hToken,
false,
&NewState,
sizeof(TOKEN_PRIVILEGES),
0,
0);

if (GetLastError()!=0)
Application->
MessageBox("Adjust Token Privilage Error","Error",MB_OK);
}



Home Index
2000 OnlineProgrammer (HtmSoft.com). All Rights Reserved