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.