我的应用程序使用第三方框架在C#中运行。它可以用作许多应用程序的UI。我的问题是我的应用程序何时运行并且系统不应发生待机/休眠OS操作。我必须以某种方式取消由OS引发的待机/休眠事件,请在这方面帮助我。

谢谢
太阳

最佳答案

blog post描述如何使用SetThreadExecutionState防止PC进入睡眠状态。代码如下:

public partial class Window1 : Window
{
    private uint m_previousExecutionState;

    public Window1()
    {
        InitializeComponent();

        // Set new state to prevent system sleep (note: still allows screen saver)
        m_previousExecutionState = NativeMethods.SetThreadExecutionState(
            NativeMethods.ES_CONTINUOUS | NativeMethods.ES_SYSTEM_REQUIRED);
        if (0 == m_previousExecutionState)
        {
            MessageBox.Show("Call to SetThreadExecutionState failed unexpectedly.",
                Title, MessageBoxButton.OK, MessageBoxImage.Error);
            // No way to recover; fail gracefully
            Close();
        }
    }

    protected override void OnClosed(System.EventArgs e)
    {
        base.OnClosed(e);

        // Restore previous state
        if (0 == NativeMethods.SetThreadExecutionState(m_previousExecutionState))
        {
            // No way to recover; already exiting
        }
    }
}

internal static class NativeMethods
{
    // Import SetThreadExecutionState Win32 API and necessary flags
    [DllImport("kernel32.dll")]
    public static extern uint SetThreadExecutionState(uint esFlags);
    public const uint ES_CONTINUOUS = 0x80000000;
    public const uint ES_SYSTEM_REQUIRED = 0x00000001;
}


如果您喜欢该帖子中描述的应用程序,则有一个更新的版本here

关于c# - 如何取消待机和休眠状态?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/823937/

10-10 07:48