PROWAREtech

articles » current » windows » application-programming-interface » shutdown-and-reboot

Windows API: Shutdown and Reboot (InitiateSystemShutdown)

How to programmatically shutdown and optionally reboot the computer; written in C/C++.

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;
}

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE