Handling System Shutdown in WPF

烂漫一生 提交于 2019-12-13 13:23:20

问题


How can I override WndProc in WPF? When my window close, I try to check if the file i'm using was modified, if so, I have to promt the user for "Do you want to save changes?" message, then close the file being used and the window.However, I cannot handle the case when user restarts/shutdown/logoff when my window is still open.I cannot override WndProc since I am developing using WPF.I have also tried using this sample MSDN code.This is what I did private void loadedForm(object sender, RoutedEventArgs e) {

  HwndSource source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
  source.AddHook(new HwndSourceHook(WndProc));

}
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{


 if (msg == WM_QUERYENDSESION.)
 {
  OnWindowClose(this, new CancelEventArgs())
  handled = true;
  shutdown = true;
 }  
 return IntPtr.Zero;    
}
private void OnWindowClose(object sender, CancelEvetArgs e)
{
   if (modified)
   {
     //show message box
     //if result is yes/no
       e.cancel = false;
     //if cancel
        e.cancel = true;
   }

}

On the XAML file, I also used Closing = "OnWindowClose" however nothing happens when I click yes/no, my application does not close. and if I try to close it again using the close button, I receive an error? why is this so? is it because of the Hook?? What is the equivalent of this in WPF?

private static int WM_QUERYENDSESSION = 0x11;
private static bool systemShutdown = false;
protected override void WndProc(ref System.Windows.Forms.Message m)
{
    if (m.Msg==WM_QUERYENDSESSION)
    {
        systemShutdown = true;
    }

    // If this is WM_QUERYENDSESSION, the closing event should be
    // raised in the base WndProc.
    base.WndProc(m);

} //WndProc 

private void Form1_Closing(
    System.Object sender, 
    System.ComponentModel.CancelEventArgs e)
{
    if (systemShutdown)
        // Reset the variable because the user might cancel the 
        // shutdown.
    {
        systemShutdown = false;
        if (DialogResult.Yes==MessageBox.Show("My application", 
            "Do you want to save your work before logging off?", 
            MessageBoxButtons.YesNo))
        {
            SaveFile();
            e.Cancel = false;
        }
        else{
            e.Cancel = true;
        }
        CloseFile();
    }
}

回答1:


Why not use the Application.SessionEnding event? That seems to be designed to do what you wish and you won't need to handle the windows message directly.

You can set Cancel to true on the SessionEndingCancelEventArgs if want to cancel the shutdown.



来源:https://stackoverflow.com/questions/1141134/handling-system-shutdown-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!