System Shutdown Processing in WPF

How can I override WndProc in WPF? When my window closes, I try to check if the file that I use has been modified, if so, I have to run the user for "Do you want to save the changes?". message, then close the used file and window. However, I cannot handle the case when the user reboots / shuts down / logs out when my window is still open. I cannot override WndProc since I am developing WPF. I 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; } } 

In 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, do I get an error message? why is that so? is it because of the hook ?? What is equivalent to 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(); } } 
+4
source share
1 answer

Why not use the Application.SessionEnding event? This is similar to what you need and you won’t need to process Windows messages directly.

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

+6
source

All Articles