4月 25, 2025 C# WPF
### 先去 CODE

可以通過引入並呼叫 `SetThreadExecutionState` 去達成防止電腦進入休眠及睡眠模式。

```c#
/**
 * application main window
 */
public partial class MainWindow : Window {

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    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,
    }
    /**
     * constructor
     */
    public MainWindow() {

        // initialize component
        InitializeComponent();

        // set startup event handler
        App.Current.Startup += new StartupEventHandler((sender, e) => {

            // keep screen awake
            SetThreadExecutionState(EXECUTION_STATE.ES_DISPLAY_REQUIRED | EXECUTION_STATE.ES_CONTINUOUS);
        });

        // set exit event handler
        App.Current.Exit += new ExitEventHandler((sender, e) => {

            // restore screen state
            SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS);
        });
    }
}
```
過去文章
2025 (9)
4 (5)
3 (1)
2 (3)
2024 (25)
11 (3)
10 (3)
9 (1)
3 (18)
2022 (6)
10 (1)
6 (2)
5 (1)
3 (1)
1 (1)
2021 (21)
11 (7)
7 (1)
6 (2)
5 (2)
4 (6)
3 (2)
2 (1)
2020 (92)
12 (1)
11 (2)
10 (4)
9 (10)
8 (5)
7 (1)
6 (3)
5 (1)
4 (4)
3 (25)
2 (7)
1 (29)
2019 (57)
12 (25)
11 (7)
9 (25)