How to disable the Sleep button while your code is running
I needed to disable the Sleep button on my keyboard, here's how.
Introduction
I am writing a small app that will allow my 2 year old daughter to play with my computer and make it so she can not change anything on it. I used a keyboard hook to capture all relevant keystrokes, but the one I was not able to capture was the Sleep key. Every time she hit the Sleep key my computer would go to sleep. Here is some code that will ensure the Sleep button is disabled while my code is running, but will restore the user settings when my code is finished running.
The CDisableSleepButton class
#include
#include
#pragma comment(lib, "powrprof")
class CDisableSleepButton
{
private:
GUID *pCurrentActivePowerScheme;
GUID *pDuplicatePowerScheme;
bool SleepButtonDisabled;
public:
CDisableSleepButton()
{
pCurrentActivePowerScheme = NULL;
pDuplicatePowerScheme = NULL;
SleepButtonDisabled = false;
DWORD Result = PowerGetActiveScheme(NULL, &pCurrentActivePowerScheme);
if (SUCCEEDED(Result))
{
Result = PowerDuplicateScheme(NULL, pCurrentActivePowerScheme, &pDuplicatePowerScheme);
if (SUCCEEDED(Result))
{
Result = PowerWriteACValueIndex(NULL,
pDuplicatePowerScheme,
&GUID_SYSTEM_BUTTON_SUBGROUP,
&GUID_SLEEPBUTTON_ACTION,
0); // Do Nothing
if (SUCCEEDED(Result))
{
Result = PowerSetActiveScheme(NULL, pDuplicatePowerScheme);
if (SUCCEEDED(Result))
{
SleepButtonDisabled = true;
}
}
if (!SleepButtonDisabled)
{
PowerDeleteScheme(NULL, pDuplicatePowerScheme);
LocalFree(pDuplicatePowerScheme);
pDuplicatePowerScheme = NULL;
}
}
}
}
~CDisableSleepButton()
{
if (SleepButtonDisabled && NULL != pCurrentActivePowerScheme)
{
DWORD Result = PowerSetActiveScheme(NULL, pCurrentActivePowerScheme);
if (SUCCEEDED(Result))
{
PowerDeleteScheme(NULL, pDuplicatePowerScheme);
LocalFree(pDuplicatePowerScheme);
pDuplicatePowerScheme = NULL;
}
}
if (NULL != pCurrentActivePowerScheme)
{
LocalFree(pCurrentActivePowerScheme);
pCurrentActivePowerScheme = NULL;
}
}
};
Using the code
Simply declare an instance of theCDisableSleepButton
class when you want the Sleep button disabled. Delete the class object, or let it go out of scope to restore the default user setting.
This code only works with Windows Vista and above, so be sure to set _WIN32_WINNT
to 0x0600
in your stdafx header file.