Let’s consider how to keep your screen awake in WinUI apps using simple C# code.

Actually, it’s very simple to do this — you just need to use the SetThreadExecutionState function.

This function is well-documented. From my experience, I can add that when using ES_CONTINUOUS, the function call applies to the calling thread. This means you should call it from a long-running thread, such as the UI thread. Otherwise, once the thread is terminated, the prevention of sleep mode will also stop. If you don’t use ES_CONTINUOUS, the SetThreadExecutionState call only resets the system idle timer. In that case, you’ll need to call this function repeatedly at regular intervals.

Here’s an example of code to enable (or disable) the “wake” mode when a ToggleButton is clicked:

private void toggle_Click(object sender, RoutedEventArgs e)
{
    var state = EXECUTION_STATE.ES_CONTINUOUS;
    if (toggle.IsChecked == true)
    {
        state |= EXECUTION_STATE.ES_DISPLAY_REQUIRED;
    }

    Windows.Win32.PInvoke.SetThreadExecutionState(state);
}

The code example is, as always, available via the link.