Calling SetThreadExecutionState before locking PC

0

I have a program which triggers evens when a user locks and unlocks their computer. I have added a function to keep the PC awake and unlocked if the user wants by calling the following code:

private void changeUnlockState()
{
    uint status = NativeMethods.SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS | EXECUTION_STATE.ES_SYSTEM_REQUIRED);    //Call ex state method with correct flags
    if (status == 0)
    {
        couldNotChangeStateError();
    }
}

internal static class NativeMethods
{
    [DllImport("kernel32.dll")]
    public static extern uint SetThreadExecutionState(EXECUTION_STATE esFlags);
}

[FlagsAttribute]
public enum EXECUTION_STATE : uint
{
    ES_AWAYMODE_REQUIRED = 0x00000040,
    ES_CONTINUOUS = 0x80000000,
    ES_DISPLAY_REQUIRED = 0x00000002,
    ES_SYSTEM_REQUIRED = 0x00000001
    // Legacy flag, should not be used.
    // ES_USER_PRESENT = 0x00000004
}

The function changeUnlockState is called when the program first starts (so the computer can't lock), is called when the user locks the computer to allow the screen to go to sleep, and again when they unlock to resume not locking the computer due to inactivity.

It appears to work fine initially, but not after the computer has been locked and unlocked. Is there some resetting of this parameter which happens automatically anyway? I have looked at the documentation, but I can't find anything about what happens if the computer is locked manually (other than it won't override user input). Should I only call the change state function on a unlock, or not at all?

c#
kernel32
asked on Stack Overflow Feb 13, 2017 by MikeS159

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0