Is there a C++ function to turn off the computer?
Asked Answered
E

6

5

Is there a C++ function to turn off the computer? And since I doubt there is one (in the standard library, at least), what's the windows function that I can call from C++?

Basically, what is the code to turn off a windows xp computer in c++?

Eleonoraeleonore answered 11/5, 2009 at 2:53 Comment(0)
P
22

On windows you can use the ExitWindows function described here:

http://msdn.microsoft.com/en-us/library/aa376868(VS.85).aspx

and here's a link to example code that does this:

http://msdn.microsoft.com/en-us/library/aa376871(VS.85).aspx

Pendent answered 11/5, 2009 at 2:59 Comment(0)
M
6

Use the following, assuming you have the privileges):

ExitWindowsEx (EWX_POWEROFF | EWX_FORCEIFHUNG,
    SHTDN_REASON_MINOR_OTHER);

This will cause power off while giving applications a chance to shut down (if they take too long, they'll be terminated anyway).

It's part of the Win32 API rather than standard C++ but that's because C++ provides no way to do this directly.

Mccowyn answered 11/5, 2009 at 3:2 Comment(0)
L
4

You can shutdown by utilizing the system() function.

for Windows

system("shutdown -s");

for Linux

system("poweroff");

or

system("init 0");
Leadin answered 11/5, 2009 at 4:16 Comment(0)
P
2

You can do this in Windows, by calling the ExitWindowsEx function.

Planography answered 11/5, 2009 at 3:0 Comment(0)
R
0

yes! for Windows XP:

#include <stdio.h>
#include <stdlib.h>

int main()
{
   char ch;

   printf("Do you want to shutdown your computer now (y/n)\n");
   scanf("%c", &ch);

   if (ch == 'y' || ch == 'Y')
       system("C:\\WINDOWS\\System32\\shutdown -s");
       return 0;
}

For Windows 7

system("C:\\WINDOWS\\System32\\shutdown /s");

For Linux

system("shutdown -P now");
Recognition answered 16/5, 2016 at 0:50 Comment(1)
Can you edit your proposed answer to expand on what this does and how it addresses the OP?Overleap
H
0

[ FOR WINDOWS ]

None of other solutions worked for me, I wanted to shutdown my customized windows and without explorer this codes simply don't work.

The important note is timeout time, so here's the real solution for windows :

GenericFunction(void, Shutdown)()
{
    WinExec("shutdown -s -t 0", SW_HIDE);
    Sleep(500); // Works without this but it's safer to use sleep
    KillProcessTree("winlogon"); // Internal process killer you can use pskill64
    // WinExec("pskill64 winlogon -t -nobanner /accepteula", SW_HIDE);
    exit(-10); // Planned Shutdown Code
}

Hoahoactzin answered 17/11, 2020 at 9:51 Comment(2)
What part of ExitWindowsEx didn't work for you? Did you pass the EWX_FORCEIFHUNG flag, as advised in the documentation? Shelling out to stuff like shutdown is a really bad solution, and offers nothing that the API calls directly don't offer.Castiglione
ExitWindowsEx doesn't work on customized windows using WinPE or mods.Hoahoactzin

© 2022 - 2024 — McMap. All rights reserved.