i have been working on a small project. i am making a timer for my little brother's PC so that he will not be able to use computer more than set time by me in a day. The problem I am facing in my code is I have tried bunch of system commands to shut down computer automatically but when it runs the command it asks to wether close the running applications. but I want to force shut down all running apps. below is the code i am trying but it is not quite working out
system("C:\\Windows\\System32\\shutdown /s /t 0");
now this statement, when it is executed, asks for closing applications which are running or cancel shut down process
ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE,
SHTDN_REASON_MAJOR_OPERATINGSYSTEM |
SHTDN_REASON_MINOR_UPGRADE |
SHTDN_REASON_FLAG_PLANNED);
i got this above function from Microsoft docs but it doesn't work in my computer even it doesn't show any error in this statement. but even after executing it doesn't work. moreover visual studio offered its own suggestion of using a new API which is given below
InitiateSystemShutdownEx(NULL, NULL, 0, true, false, SHTDN_REASON_FLAG_USER_DEFINED);
this also doesn't work even if gets execute. i am using windows 11. and below i am giving the whole code where i reached yet
#include <iostream>
#include <stdlib.h>
#include<Windows.h>
#include<fstream>
#pragma warning(disable : 4996)
#pragma comment(lib, "user32.lib")
#pragma comment(lib, "advapi32.lib")
using namespace std;
void timer()
{
int hours=0;
int minutes=0;
int seconds=0;
ofstream tim;
while (seconds != 5)
{
tim.open("time.txt", ios::out | ios::trunc);
seconds ;
Sleep(1000);
if (seconds == 60)
{
minutes ;
seconds = 0;
}
if (minutes == 60)
{
hours ;
minutes = 0;
}
tim << hours << endl << minutes << endl << seconds;
tim.close();
}
}
int main()
{
timer();
ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE,
SHTDN_REASON_MAJOR_OPERATINGSYSTEM |
SHTDN_REASON_MINOR_UPGRADE |
SHTDN_REASON_FLAG_PLANNED);
cout << endl << endl;
return 0;
}
so please just any type of help would be appreciated.
CodePudding user response:
You need to add the /f
flag to force a shutdown.
CodePudding user response:
Here's the actual logoff function I created many years ago when faced with a similar problem. There's a lot of extra code there to support debugging without logging myself out, the actual work is in the call to ExitWindowsEx
.
void CTimeLimitApp::Logoff()
{
static bool bOff = false;
if (bOff)
return;
bOff = true;
#if _DEBUG
AfxMessageBox("Logoff!", MB_OK, 0);
PostQuitMessage(0);
#else
Sleep(1000);
ExitWindowsEx(EWX_LOGOFF | EWX_FORCE, 0);
#endif
}
You may need to run the program as Administrator if you want to do a full shutdown.