Archived

This topic is now archived and is closed to further replies.

How To ShutDown?

This topic is 5655 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I would like to know how to shutdown My PC (running under Windows) with C (or simple C++) code. Let me know if there are functions to operate that. Thx I''''m 4 & I draw

Share this post


Link to post
Share on other sites

  bool AdjustToken(bool bEnable)
{
HANDLE hToken = NULL;

if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken))
{
printf("OpenProcessToken(...) failed, error code %lu\n", GetLastError());
}
else
{
TOKEN_PRIVILEGES tp;
LUID luid;

if (!LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &luid))
{
printf("LookupPrivilegeValue(...) failed, error code %lu\n", GetLastError());
}
else
{
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = (bEnable) ? SE_PRIVILEGE_ENABLED : 0;

BOOL bResult = AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), NULL, NULL);
DWORD dwError = GetLastError();

if (!bResult || (dwError != ERROR_SUCCESS))
{
printf("AdjustTokenPrivileges(...) failed, error code %lu\n", dwError);
}
else
{
CloseHandle(hToken);
return true;
}
}

CloseHandle(hToken);
}

return false;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
if (!AdjustToken(true))
{
printf("AdjustToken(...) failed\n");
}
else
{
if (!ExitWindowsEx(EWX_POWEROFF | EWX_FORCEIFHUNG, 0))
{
printf("ExitWindowsEx(...) failed\n");
}
else
{
printf("Shutting down Windows. Goodbye.\n");
}

if (!AdjustToken(false))
{
printf("AdjustToken(...) failed\n");
}
}

return 0;
}

Share this post


Link to post
Share on other sites
EWX_FORCEIFHUNG is only for Windows 2000/XP. You need the following define before you include windows.h.
#define _WIN32_WINNT 0x0500
#include <Windows.h>


[edited by - dalleboy on June 25, 2002 11:38:44 AM]

Share this post


Link to post
Share on other sites