您可以调用 HwndSource.AddHook 来处理 Win32 消息以获取关闭窗口的原因。就像是:
Window myWindow = new Window();
myWindow .Loaded += delegate
{
HwndSource source = (HwndSource)PresentationSource.FromDependencyObject(myWindow );
source.AddHook(WindowProc);
};
以及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;
}
你有一个所有 Windows 消息的列表
WM_SYSCOMMND 的 wParam 值
希望这可以帮助。