views:

806

answers:

1

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();
    }
}
A: 

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.

Ray