PROWARE technologies
PROWARE technologies

Windows API Shutdown (InitiateSystemShutdown)

This code will shutdown and optionally reboot your machine. The user needs to be allowed to shutdown the computer so his privileges need to be adjusted.

#include <windows.h>

BOOL Shutdown(BOOL bReboot)
{
	HANDLE hToken;
	TOKEN_PRIVILEGES tkp;

	if(!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
		return FALSE;

	LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid);

	tkp.PrivilegeCount = 1;
	tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

	// need to adjust privileges to allow user to shutdown
	if(!AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES) NULL, 0))
		return FALSE;

	if(!InitiateSystemShutdown(NULL, NULL, 0, TRUE, bReboot))
		return FALSE;

	tkp.Privileges[0].Attributes = 0;

	AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES) NULL, 0);

	return TRUE;
}

int main(int argc, char **argv)
{
	Shutdown(TRUE);
	return 0;
}
Contact