Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF: How to distinguish between Window.Close() call and system menu Close action? [duplicate]

Tags:

c#

.net

wpf

xaml

Possible Duplicate:
How to distinguish ‘Window close button clicked (X)’ vs. window.Close() in closing handler

In WPF, here are different ways to close a Window:

1) Window.Close()
2) Select 'Close' from Window system menu (top left)
3) Click 'X' button on Window title bar (top right)
4) Keyboard shortcut: Alt+F4

All of these actions trigger WPF event Window.Closing

How do I distinguish between these two types of actions?

In Excel/VBA this is possible: VBA.VbQueryClose.vbFormCode vs VBA.VbQueryClose.vbFormControlMenu.

This related question/answer says the system menu actions will generate Windows event WM_CLOSE. Perhaps there is a way to see the underlying Windows event from WPF.

like image 576
kevinarpe Avatar asked Dec 21 '22 12:12

kevinarpe


2 Answers

You can call HwndSource.AddHook to process Win32 message to get close reason of a Window. Something like:

Window myWindow = new Window();
myWindow .Loaded += delegate
{
    HwndSource source = (HwndSource)PresentationSource.FromDependencyObject(myWindow );
    source.AddHook(WindowProc);
};

And the implementation of the WindowProc:

    private static IntPtr WindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam,      
      ref bool handled){
     switch (msg)
     {
         case: 0x10:
              Console.WriteLine("Close reason: Clicking X");
         case 0x11:
         case 0x16:
             Console.WriteLine("Close reason: WindowsShutDown");
             break;

         case 0x112:
             if (((ushort)wParam & 0xfff0) == 0xf060)
                 Console.WriteLine("Close reason: User closing from menu");
             break;
     }
     return IntPtr.Zero;
    }

And you have a list of all Windows messages

Values for wParam for WM_SYSCOMMND

Hope this helps.

like image 151
MBen Avatar answered Feb 01 '23 23:02

MBen


One simple option is to set some flag before calling Window.Close yourself.

like image 30
Alexei Levenkov Avatar answered Feb 01 '23 23:02

Alexei Levenkov