How to turn off pc via windows API?

Night Walker picture Night Walker · Oct 1, 2009 · Viewed 8.4k times · Source

I never programmed a winapi so i have a little problem here .

I need turn off my pc from my application .

I found this example link text then i found this example how to change privileges link text

But i have problem how to get that parameter HANDLE hToken // access token handle

I think i need to make it in the next order to get the parameter OpenProcessToken LookupPrivilegeValue AdjustTokenPrivileges but there are a lot parameters that i have no idea what to do with them .

maybe you have jere some example how i get that HANDLE hToken parameter to make that work .

By the way I already saw the following post link text

Thanks a lot all you .

Answer

Lior Kogan picture Lior Kogan · Oct 1, 2009
// ==========================================================================
// system shutdown
// nSDType: 0 - Shutdown the system
//          1 - Shutdown the system and turn off the power (if supported)
//          2 - Shutdown the system and then restart the system
void SystemShutdown(UINT nSDType)
{
    HANDLE           hToken;
    TOKEN_PRIVILEGES tkp   ;

    ::OpenProcessToken(::GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY, &hToken);
    ::LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid);

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

    // get the shutdown privilege for this process
    ::AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0);

    switch (nSDType)
    {
        case 0: ::ExitWindowsEx(EWX_SHUTDOWN|EWX_FORCE, 0); break;
        case 1: ::ExitWindowsEx(EWX_POWEROFF|EWX_FORCE, 0); break;
        case 2: ::ExitWindowsEx(EWX_REBOOT  |EWX_FORCE, 0); break;
    }
}