0

I'm trying to detect the Windows LogOff or Shutdown in my WPF application. Can someone help?

xaml.cs

private static int WM_QUERYENDSESSION = 0x11;
private static bool systemShutdown = false;
public static event Microsoft.Win32.SessionEndingEventHandler SessionEnding;

protected virtual void WndProc(ref System.Windows.Forms.Message m)
{
    if (m.Msg == WM_QUERYENDSESSION)
    {
        MessageBox.Show("queryendsession: this is a logoff, shutdown, or reboot");
        systemShutdown = true;
    }

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

} //WndProc

Error: RadWindow does not contain a definition for 'WndProc'

hensing1
  • 187
  • 13
A Coder
  • 3,039
  • 7
  • 58
  • 129
  • Possible duplicate of [Catch windows shutdown event in a wpf application](https://stackoverflow.com/questions/7136573/catch-windows-shutdown-event-in-a-wpf-application) – Nawed Nabi Zada Feb 22 '19 at 11:31

1 Answers1

1

You should be able to get a reference to the parent WPF window and create a Win32 hook once your RadWindow has been loaded:

public class MyRadWindow : RadWindow
{
    public MyRadWindow()
    {
        Loaded += MyRadWindow_Loaded;
    }

    private void MyRadWindow_Loaded(object sender, System.Windows.RoutedEventArgs e)
    {
        System.Windows.Window wpfWindow = this.ParentOfType<System.Windows.Window>();
        HwndSource source = HwndSource.FromHwnd(new WindowInteropHelper(wpfWindow).Handle);
        source.AddHook(new HwndSourceHook(WndProc));
    }

    private const int WM_QUERYENDSESSION = 0x11;
    private static IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        if (msg == WM_QUERYENDSESSION)
        {
            //...
        }

        return IntPtr.Zero;
    }

    ...
}
mm8
  • 163,881
  • 10
  • 57
  • 88
  • Great!!! Yes, this worked for me. One thing is, the event fires for both Shutdown and Cancel. Is there anyway to fire it only for shutdown? Also, I need this to be done in MVVM way. Can you please help on that? – A Coder Feb 26 '19 at 12:00
  • @iamCR: Please ask a new question if you have another issue. Your original question was about how to detect the events in a `RadWindow` and nothing else. – mm8 Feb 26 '19 at 12:12