c++ win32 关机 注销 重启

#include <iostream>
#include <Windows.h>

#pragma comment(lib, "user32.lib")
#pragma comment(lib, "advapi32.lib")

int main()
{
	// https://docs.microsoft.com/en-us/windows/win32/shutdown/how-to-shut-down-the-system

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

	// 获取关闭特权的LUID
	TOKEN_PRIVILEGES tkp;
	LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid);

	tkp.PrivilegeCount = 1;  // one privilege to set    
	tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

	// 获取此过程的关闭特权。
	AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0);

	if (GetLastError() != ERROR_SUCCESS)
	{
		CloseHandle(hToken);
		return FALSE;
	}

	// 关闭系统并强制关闭所有应用程序。
	// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-exitwindowsex

	//DWORD uFlags = EWX_SHUTDOWN | EWX_FORCE; // 关机
	//DWORD uFlags = EWX_LOGOFF | EWX_FORCE; // 注销
	DWORD uFlags = EWX_REBOOT | EWX_FORCE; // 重启
	if (!ExitWindowsEx(uFlags,
		SHTDN_REASON_MAJOR_OPERATINGSYSTEM |
		SHTDN_REASON_MINOR_UPGRADE |
		SHTDN_REASON_FLAG_PLANNED))
	{
		CloseHandle(hToken);
		return FALSE;
	}

	// 关闭成功
	return 0;
}
posted @ 2020-09-03 15:11  Ajanuw  阅读(459)  评论(0编辑  收藏  举报