【问题标题】:Detect PowerModeChange and wait for execution检测 PowerModeChange 并等待执行
【发布时间】:2015-05-14 20:02:19
【问题描述】:

我想在计算机挂起时运行一些保存程序。因此,我使用 OnPowerChange-Event 来检测它何时暂停和恢复。不幸的是,我保存例程需要 3-5 秒才能执行。

当我收到挂起事件时,计算机会在 1-2 秒内关闭,并且我的例程没有完全执行。

在我的例程完成之前如何防止暂停?

SystemEvents.PowerModeChanged += OnPowerChange;


private void OnPowerChange(object s, PowerModeChangedEventArgs e)
{

    switch (e.Mode)
    {
        case PowerModes.Resume:
            switchEdifier(true);
            break;
        case PowerModes.Suspend:
            switchEdifier(false);
            break;
    }
}

【问题讨论】:

    标签: c# winapi power-management win32-process


    【解决方案1】:

    有一些非托管 API 可以帮助解决这个问题,特别是 ShutdownBlockReasonCreateShutdownBlockReasonDestroy

    需要注意的是,这两个函数必须配对,当你调用一个时,你必须确保你调用了另一个(例如,在发生异常时),否则关机可能会被无限期阻止。

    这将导致显示一个对话框,告诉用户哪些程序正在阻止关机,以及阻止关机的原因。快速完成工作并离开很重要,因为用户可以选择点击他们经常使用的“强制关机”按钮。

    这是一个使用它的例子:

    [DllImport("user32.dll", SetLastError=true)]
    static extern bool ShutdownBlockReasonCreate(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)] string reason);
    
    [DllImport("user32.dll", SetLastError=true)]
    static extern bool ShutdownBlockReasonDestroy(IntPtr hWnd);
    
    //The following needs to go in a Form class, as it requires a valid window handle
    public void BlockShutdownAndSave()
    {
        //If calling this from an event, you may need to invoke on the main form
        //because calling this from a thread that is not the owner of the Handle
        //will cause an "Access Denied" error.
    
        try
        {
            ShutdownBlockReasonCreate(this.Handle, "You need to be patient.");
            //Do your saving here.
        }
        finally
        {
            ShutdownBlockReasonDestroy(this.Handle);
        }
    }
    

    鼓励使用短字符串,因为用户通常不会阅读长消息。引起注意的内容,例如“保存数据”或“将更改刷新到磁盘”。请注意“无论如何我是一个不耐烦的用户”按钮。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-21
      • 2022-12-18
      • 2016-09-13
      • 2012-05-03
      • 1970-01-01
      • 1970-01-01
      • 2021-06-10
      相关资源
      最近更新 更多