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.
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.
One simple option is to set some flag before calling Window.Close
yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With