[Win32] SetThreadExecutionState

Win32 API の SetThreadExecutionState による Windows スクリーンセーバーおよびスリープへの移行を抑制する方法について記載します。

 

 

 

1. c++ サンプル

[概要]

プログラム起動中、スクリーンセーバーおよびスリープを発生しないようにするプログラムを作成します。[Enter] キーを押してプログラムを終了すると元の状態へ戻ります。

コンソールプログラムとして c/c++ でサンプルプログラムを作成します。

 

[環境]

コンパイラ : Visual Studio 2022 pro., Version 16.6.0
プログラミング言語 : c++  
フレームワーク : native  
OS : Windows11 home, 22H2

 

//
// Refer to the following URL for details of api SetThreadExecutionState.
// https://learn.microsoft.com/ja-jp/windows/win32/api/winbase/nf-winbase-setthreadexecutionstate
//

#include <iostream>
#include <windows.h>

int main()
{
    EXECUTION_STATE es;

    do {
        //
        // Enable away mode and prevent the sleep idle time-out.
        //
        std::cout << "Now enable away mode and prevent the sleep idle time-out." << std::endl;
        es = SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED);
        if (es == NULL) {
            MessageBox(NULL, L"ERROR happen.", L"ERROR", MB_OK | MB_ICONSTOP);
            break;
        }

        std::cout << std::endl;
        std::cout << "Push [Enter] key" << std::endl;
        std::cout << "to clear EXECUTION_STATE flags to disable away mode and allow the system to idle to sleep normally. ";
        std::cin.get();
        std::cout << "Done," << std::endl;
    } while (0);


    //
    // Clear EXECUTION_STATE flags (ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED) 
    // to disable away mode and allow the system to idle to sleep normally.
    //
    SetThreadExecutionState(ES_CONTINUOUS);

    return EXIT_SUCCESS;
}

 

 

2. c# サンプル

[概要]

プログラム起動中、スクリーンセーバーおよびスリープを発生しないようにするプログラムを作成します。[Enter] キーを押してプログラムを終了すると元の状態へ戻ります。

コンソールプログラムとして c# でサンプルプログラムを作成します。

 

[環境]

コンパイラ : Visual Studio 2022 pro., Version 16.6.0
プログラミング言語 : c#  
フレームワーク : .NET 6.0
  .NET Framework 4.8
OS : Windows11 home, 22H2

 

//
// Refer to the following URL for details of api SetThreadExecutionState.
// https://learn.microsoft.com/ja-jp/windows/win32/api/winbase/nf-winbase-setthreadexecutionstate
// https://www.pinvoke.net/default.aspx/kernel32/SetThreadExecutionState.html
//

using System.Runtime.InteropServices;


namespace SetThreadExecutionStateTest
{
    class SetThreadExecutionStateTestClass
    {
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [DefaultDllImportSearchPaths(DllImportSearchPath.UserDirectories)]
        static extern EXECUTION_STATE 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
        }


        /// <summary>
        /// Main function.
        /// </summary>
        /// <param name="args"></param>
        static void Main()
        {
            PreventMonitorPowerdown();

            // Display message and wait for [Enter] key down.
            Console.WriteLine("Push [Enter] key");
            Console.Write("to clear EXECUTION_STATE flags to disable away mode and allow the system to idle to sleep normally. ");
            Console.ReadLine();

            AllowMonitorPowerdown();
        }

        /// <summary>
        /// このメソッドを実行することで、スクリーンセーバーおよびスリープへの移行を抑制します。
        /// 解除する場合はメソッド AllowMonitorPowerdown を実行します。
        /// </summary>
        static void PreventMonitorPowerdown()
        {
            SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS | EXECUTION_STATE.ES_DISPLAY_REQUIRED | EXECUTION_STATE.ES_SYSTEM_REQUIRED);
        }

        /// <summary>
        /// EXECUTION_STATE 設定を解除します。
        /// </summary>
        static void AllowMonitorPowerdown()
        {
            SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS);
        }

        /// <summary>
        /// 退席モードを有効にします。この値は 、ES_CONTINUOUSで指定する必要があります。
        /// 解除する場合はメソッド AllowMonitorPowerdown を実行します。
        /// 退席モードは、コンピューターがスリープ状態になっているように見える間、
        /// デスクトップ コンピューターで重要なバックグラウンド処理を実行する必要がある
        /// メディア記録およびメディア配布アプリケーションでのみ使用する必要があります。
        /// </summary>
        static void PreventSleep()
        {
            // Prevent Idle-to-Sleep (monitor not affected)
            SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS | EXECUTION_STATE.ES_AWAYMODE_REQUIRED);
        }
    }
}

 


ライセンス

本ページの情報は、特記無い限り下記 MIT ライセンスで提供されます。

The MIT License (MIT)

Copyright 2023 Kinoshita Hidetoshi

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

 

 

参考

 


 

変更履歴

2023-03-08 - 新規作成

 

Programming Items トップページ

プライバシーポリシー