Loading color scheme

How to shutdown a computer programmatically in Windows

If you are writing some installer application, want to update system files, apply settings of for some other reason, you may need to shutdown (reboot, power off) a Windows 10 computer. The good news is that Windows has a pretty straightforward API for this intent, which is called ExitWindowsEx. It has only two parameters. The first one is the flags parameter which you can set to either reboot or power-off and the second one - the reboot reason, which is only used on servers and is not mandatory.  But the bad news is that the functions won't work as-is. In order to make it work, you need to enable the shutdown privilege, which is disabled by default. I advise you to enable this privilege only directly before you decide to shut down. 

So here comes the working code to reboot or shutdown Windows 10



// Reboot Windows 
EnableShutdownPrivilege(TRUE);
ExitWindowsEx(EWX_REBOOT,0);

// Shutdown Windows
EnableShutdownPrivilege(TRUE);
ExitWindowsEx(EWX_POWEROFF|EWX_SHUTDOWN,0);

// if you need to forcefully close all applications before the shutdown, add the EWX_FORCE flag


BOOL EnableShutdownPrivilege(BOOL bEnable)
{
	HANDLE hToken = NULL; 
	TOKEN_PRIVILEGES tkp; 
	BOOL bRet = FALSE;
 
	// Get a token for this process. 
 	if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
	{
	 	// Get the LUID
 		if (LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid))
		{
			tkp.PrivilegeCount = 1;  // one privilege to set    
			if (bEnable)
				tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; 
			else
				tkp.Privileges[0].Attributes = 0; 

			bRet = AdjustTokenPrivileges(hToken, FALSE, &tkp, sizeof(TOKEN_PRIVILEGES), NULL, NULL);
		}	
		
		CloseHandle(hToken);
	}

	return bRet;
}
Get all interesting articles to your inbox
Please wait