i need code that will allow me to restart shutdown or logoof the computer (saftley)

Dani AI

Generated

Short answer for (and thanks to for the link): on Win32 use ExitWindowsEx for interactive logoff/shutdown/reboot; it sends WM_QUERYENDSESSION to running apps so they can save or block the shutdown. For shutdown/reboot the process must first enable the shutdown privilege (SeShutdownPrivilege / SE_SHUTDOWN_NAME) — logoff (EWX_LOGOFF) does not need that extra step. Avoid EWX_FORCE unless it’s an emergency because it can cause data loss. ExitWindowsEx documentation. (learn.microsoft.com) WM_QUERYENDSESSION details. (learn.microsoft.com)

Minimal, practical pattern (enable the privilege, then call ExitWindowsEx). The sequence is: OpenProcessToken → LookupPrivilegeValue(SE_SHUTDOWN_NAME) → AdjustTokenPrivileges to enable it → call ExitWindowsEx with EWX_SHUTDOWN / EWX_REBOOT (check GetLastError for failures). A simple C++ outline:

#include <windows.h>

bool SafeShutdown()
{
    HANDLE hToken = NULL;
    if (!OpenProcessToken(GetCurrentProcess(),
         TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) return false;

    TOKEN_PRIVILEGES tp = {0};
    if (!LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tp.Privileges[0].Luid))
    { CloseHandle(hToken); return false; }
    tp.PrivilegeCount = 1;
    tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
    AdjustTokenPrivileges(hToken, FALSE, &tp, 0, NULL, NULL);
    CloseHandle(hToken);
    if (GetLastError() != ERROR_SUCCESS) return false;

    return ExitWindowsEx(EWX_SHUTDOWN, SHTDN_REASON_MAJOR_OTHER | SHTDN_REASON_FLAG_PLANNED) != FALSE;
}

See the official guide on enabling privileges and a worked shutdown example for details and error handling. Enabling/disabling privileges sample (learn.microsoft.com) How to shut down the system example. (learn.microsoft.com)

Notes: from services, scheduled tasks, or non-interactive sessions use InitiateShutdown / InitiateSystemShutdownEx (they’re designed for remote/non-interactive shutdowns and offer timeout dialogs). Shutdown requests are asynchronous and can be aborted; choose force flags only when absolutely necessary. InitiateShutdown reference. (learn.microsoft.com)

Recommended Answers

All 4 Replies

thats confusing its and spanish that engilish i dont know whats what could u help me clear it up

Bump

There is indeed some spanish in the first guy's post.
But the answers are in PERFECTLY UNDERSTANDABLE english.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.