qt在window上控制电脑关机重启操作

一、前言

qt控制window系统的关机重启,Linux等其余设备需调用不同系统的api函数去操作,本文只介绍基于windows系统环境。

二、环境

win8系统,qt5.7

三、正文

我的用法是在退出程序是询问是否要关机

void MainWindow::closeEvent(QCloseEvent *event)
{
    QMessageBox msgBox(QMessageBox::Question,
                       "关闭", "是否关机",
                       QMessageBox::Yes |QMessageBox::Cancel,NULL);
    msgBox.setDefaultButton(QMessageBox::Yes);//默认选择ok,如果按回车执行ok选项
    int ret = msgBox.exec();
    switch (ret) {
      case QMessageBox::Yes:
            event->accept();
            MySystemShutDown(false);
          break;
      case QMessageBox::Cancel:
            event->ignore();
          break;
      default:
          break;
    }
}
//true:重启  false:关机
bool MainWindow::MySystemShutDown(bool reset)
{
     HANDLE hToken;
     TOKEN_PRIVILEGES tkp;
     // Get a token for this process.
     if (!OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
     return(FALSE);
     // Get the LUID for the shutdown privilege.
     LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME,&tkp.Privileges[0].Luid);
     tkp.PrivilegeCount = 1;  // one privilege to set
     tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
     // Get the shutdown privilege for this process.
     AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,(PTOKEN_PRIVILEGES)NULL, 0);
     if (GetLastError() != ERROR_SUCCESS)
     return FALSE;
     // Shut down the system and force all applications to close.
     if(!reset){//关机
         if (!ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE,
         SHTDN_REASON_MAJOR_OPERATINGSYSTEM |
         SHTDN_REASON_MINOR_UPGRADE |
         SHTDN_REASON_FLAG_PLANNED));
     }
     //restart the system
     else {//重启
         if(!ExitWindowsEx(EWX_REBOOT | EWX_FORCE, 0));
     }
     //return FALSE;
     //shutdown or restart was successful
     return TRUE;
}

 mainwindow.h

private slots:
    void closeEvent(QCloseEvent *event);
    bool MySystemShutDown(bool reset);

你可能感兴趣的:(#,qt控制关机,qt,window,shut,down)