我想在计算机挂起时运行一些保存例程。因此,我使用OnPowerChange事件来检测其挂起和恢复的时间。不幸的是,我保存例行程序需要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;
}
}发布于 2015-05-14 20:43:00
有一些非托管API可以帮助解决这个问题,特别是ShutdownBlockReasonCreate和ShutdownBlockReasonDestroy。
需要注意的是,这两个函数必须配对,当您调用一个函数时,必须确保调用另一个函数(例如,在异常情况下),否则关闭可能会被无限期阻止。
这将导致一个对话框显示,告诉用户哪些程序正在阻止关闭,以及关闭的原因。重要的是你迅速完成你的工作,然后离开,因为用户可以选择点击“强制关闭”按钮,这是他们经常使用的。
下面是一个使用它的示例:
[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);
}
}由于这个原因,鼓励使用短字符串,因为用户通常不会读取长消息。吸引注意力的东西,如“保存数据”或“冲入磁盘”。只要记住“无论如何,我是一个不耐烦的用户”按钮。
https://stackoverflow.com/questions/30246298
复制相似问题