using System.Windows;
using Microsoft.Win32;
namespace CatchHibernateMsg
{
/// <summary>
/// We will catch system's suspend and resume events by adding handlers in Microsoft.Win32.SystemEvents's static events.
/// So that when you suspend or resume your computer,it shall show a dialog to inform you.
/// </summary>
public partial class MainWindow : Window
{
SessionEndedEventHandler seeh;
PowerModeChangedEventHandler pmceh;
public MainWindow()
{
InitializeComponent();
addEventsHandlers();
}
private void addEventsHandlers()
{
this.Closing += new System.ComponentModel.CancelEventHandler(MainWindow_Closing);
seeh = new SessionEndedEventHandler(SystemEvents_SessionEnded);
pmceh = new PowerModeChangedEventHandler(SystemEvents_PowerModeChanged);
SystemEvents.SessionEnded += seeh;
SystemEvents.PowerModeChanged += pmceh;
}
void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
detachEventHandlers();
}
// Since SessionEnded and PowerModeChanged is static events,we will need to detach the events handlers in exiting.
private void detachEventsHandlers()
{
if (pmceh != null) SystemEvents.SessionEnded -= this.seeh;
if (pmceh != null) SystemEvents.PowerModeChanged -= this.pmceh;
}
void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
{
if (e.Mode == PowerModes.Suspend)
pause();
else if(e.Mode == PowerModes.Resume)
continu();
}
private void pause() { MessageBox.Show("pause"); }
private void continu() { MessageBox.Show("continue"); }
void SystemEvents_SessionEnded(object sender, SessionEndedEventArgs e)
{
Application.Current.Shutdown(0);
}
}
}