How do I turn off the windows screen saver if it is running using C#?

前端 未结 4 719
无人共我
无人共我 2021-01-19 20:21

Ok, so I found some code to check if a screensaver is running and kill it if I want to. This doesn\'t seem to work on Windows 7 PCs. Does anyone know how this code can be mo

4条回答
  •  再見小時候
    2021-01-19 21:12

    Use SetThreadExecutionState this winAPI to tell the operating system that the thread is in use, even if the user is not interacting with the computer. These will prevent to appear screen saver and stop the machine from being suspended automatically.

    Enables an application to inform the system that it is in use, thereby preventing the system from entering sleep or turning off the display while the application is running.

    There are series of flags to specify a new state for the current thread:

    • ES_AWAYMODE_REQUIRED (0x00000040) : Enables away mode.
    • ES_DISPLAY_REQUIRED (0x00000002) : Forces the display to be on by resetting the display idle timer.
    • ES_SYSTEM_REQUIRED (0x00000001) : Forces the system to be in the working state by resetting the system idle timer.
    • ES_CONTINUOUS (0x80000000) : Informs the system that the state being set should remain in effect until the next call that uses ES_CONTINUOUS and one of the other state flags is cleared.

    As this is an winAPI, so you have to PInvoke this :

    [DllImport("kernel32.dll", CharSet = CharSet.Auto,SetLastError = true)]
    static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);
    

    User-Defined Types:

    [FlagsAttribute]
    public enum EXECUTION_STATE :uint
    {
       ES_AWAYMODE_REQUIRED = 0x00000040,
       ES_CONTINUOUS = 0x80000000,
       ES_DISPLAY_REQUIRED = 0x00000002,
       ES_SYSTEM_REQUIRED = 0x00000001
    }
    

    Here below is the calling procedure:

    //To stop screen saver and monitor power off event
    //You can combine several flags and specify multiple behaviors with a single call
    SetThreadExecutionState(EXECUTION_STATE.ES_DISPLAY_REQUIRED | EXECUTION_STATE.ES_SYSTEM_REQUIRED | EXECUTION_STATE.ES_CONTINUOUS);
    
    //To reset or allow those event again you have to call this API with only ES_CONTINUOUS
    SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS);//This will reset as normal
    

    According to MSDN this API is safe to use.

    The system maintains a count of applications that have called SetThreadExecutionState. The system tracks each thread that calls SetThreadExecutionState and adjusts the counter accordingly. If this counter reaches zero and there has not been any user input, the system enters sleep.

    If the Application crashed before resetting flag, the System will adjust and will reset automatically.

提交回复
热议问题