且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

防止Windows工作站(桌面)在运行WPF程序时锁定

更新时间:2023-10-05 09:31:52

已通过注释指出了解决方案,但我将不胜感激。我为通过网络搜索到达的其他任何人提供了一个简单的入门解决方案:

The solution has been pointed out through the comments, but I'm providing a simple starter solution for anyone else arriving via a web search:

/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);

    public App()
    {
        InitializeComponent();

        App.Current.Startup += new StartupEventHandler((sender, e) =>
            {
                SetThreadExecutionState(EXECUTION_STATE.ES_DISPLAY_REQUIRED | EXECUTION_STATE.ES_CONTINUOUS);
            });
        App.Current.Exit += new ExitEventHandler((sender, e) =>
            {
                SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS);
            });
    }
}

[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
}

放置逻辑的另一个地方将在您的主应用程序窗口中位于 StateChanged 的事件处理程序内:

An alternative place to put the logic would be within an event handler for StateChanged on your main application window:

this.StateChanged += new EventHandler((sender, e) =>
    {
        if (WindowState == System.Windows.WindowState.Maximized)
        {
            SetThreadExecutionState(EXECUTION_STATE.ES_DISPLAY_REQUIRED | EXECUTION_STATE.ES_CONTINUOUS);
        }
        else
        {
            SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS);
        }
    });