C++写开关机程序(控制台程序)

本文涉及到WIN10权限提升相关的方法:

#include <pch.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <conio.h>
#include <ctype.h>
#include <iostream>
#include <windows.h>


using namespace std;

/*
提升进程权限
*/
bool improvePv()
{
  HANDLE hToken;
  TOKEN_PRIVILEGES tkp;
  if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &hToken)) return false;
  if (!LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid)) return false;
  tkp.PrivilegeCount = 1;
  tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  if (!AdjustTokenPrivileges(hToken, FALSE, &tkp, NULL, NULL, NULL)) return false;
  return true;
}

/*
关机
*/
bool powerOffProc()
{
  if (!improvePv() || !ExitWindowsEx(EWX_POWEROFF | EWX_FORCE, SHTDN_REASON_MAJOR_APPLICATION)) return false;
  return true;
}

/*
注销
*/
bool logOffProc()
{
  if (!improvePv() || !ExitWindowsEx(EWX_LOGOFF | EWX_FORCE, SHTDN_REASON_MAJOR_APPLICATION)) return false;
  return true;
}

/*
重启
*/
bool reBootProc()
{
  if (!improvePv() || !ExitWindowsEx(EWX_REBOOT | EWX_FORCE, SHTDN_REASON_MAJOR_APPLICATION)) return false;
  return true;
}

int main(void)
{
  CHAR ch;
  printf(">>>>>>>>>>>>>>>>>>>>>> Demo >>>>>>>>>>>>>>>>>\n*\n");
  printf("* 1. Power_Off\n*\n");
  printf("* 2. Log_Off\n*\n");
  printf("* 3. ReBoot\n*\n");
  printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
  ch = _getch();
  while (1)
  {
    switch (ch)
    {
    case '1':
      if (!powerOffProc())
      {
        printf("Process Error!\n");
        continue;
      }
      return 0;
    case '2':
      if (!logOffProc())
      {
        printf("Process Error!\n");
        continue;
      }
      return 0;
    case '3':
      if (!reBootProc())
      {
        printf("Process Error!\n");
        continue;
      }
      return 0;
    default:
      printf("Error!\n");
    }
  }
  system("pause");
  return 0;
}

 

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注