This is a little how-to that explains how to shutdown or reboot a Windows machine in c++ .
In the source code you will find the function ShutDown, definied as follow:

bool ShutDown(bool restart)

The function shutdowns or reboots the pc, and returns false if the shutdown can’t be done (for example a process denied the power off).

Shut Down

So, to shutdown the pc, you only have to call the function and check if the shutdown was done.

if (!ShutDown(false))
{
	// shutdown not done.
}

Part of source code following:

HANDLE hToken;
TOKEN_PRIVILEGES tkp;
// get process token
OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken);
// get shutdown privileges
LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid);
tkp.PrivilegeCount = 1;	// devo settare 1 privilegio
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
// setting privileges
AdjustTokenPrivileges(hToken, false, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
...
// shutdown the system and force all application to close
ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCEIFHUNG,
		SHTDN_REASON_MAJOR_OPERATINGSYSTEM |
		SHTDN_REASON_MINOR_UPGRADE |
		SHTDN_REASON_FLAG_PLANNED);

You can download the complete source code from here:

Download [Download not found]. Downloads: [Download not found]


Se sei interessato a questo post, potresti anche provare a leggere:

  • No related posts