分类: C/C++
2008-08-04 09:30:51
BOOL SetSystemPowerState( BOOL fSuspend, // system state BOOL fForce // forced suspension option );真是好东东,比关机器还好,在任何情况下都可以切断电源(这正是我想要的),也不会有讨厌的提示。
函数很简单,但直接用不好使,前面得加些罗哩八嗦的东东,所以我就进行了一下封装。
void PERR(LPTSTR szAPI, DWORD dwLastError); #define RTN_ERROR 13 INT SetPower() { // TODO: Add your control notificationhandler code here TOKEN_PRIVILEGES tp; HANDLE hToken; LUID luid; LPTSTR MachineName=NULL; // pointer to machine name if(!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken )) { PERR("OpenProcessToken", GetLastError() ); return RTN_ERROR; } if(!LookupPrivilegeValue(MachineName, SE_SHUTDOWN_NAME, &luid)) { PERR("LookupPrivilegeValue", GetLastError() ); return RTN_ERROR; } tp.PrivilegeCount = 1; tp.Privileges[0].Luid = luid; tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), NULL, NULL ); SetSystemPowerState(FALSE,TRUE); return 0; }
void PERR( LPTSTR szAPI, // pointer to failed API name DWORD dwLastError // last error value associated with API ) { LPTSTR MessageBuffer; DWORD dwBufferLength; // // TODO get this fprintf out of here! // fprintf(stderr,"%s error! (rc=%lu)\n", szAPI, dwLastError); if(dwBufferLength=FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, dwLastError, LANG_NEUTRAL, (LPTSTR) &MessageBuffer, 0, NULL)) { DWORD dwBytesWritten; // // Output message string on stderr // WriteFile(GetStdHandle(STD_ERROR_HANDLE), MessageBuffer, dwBufferLength, &dwBytesWritten, NULL); // // free the buffer allocated by the system // LocalFree(MessageBuffer); } }