WPF:如何区分Window.Close()调用和系统菜单“关闭”操作? [英] WPF: How to distinguish between Window.Close() call and system menu Close action?
问题描述
Possible Duplicate:
How to distinguish ‘Window close button clicked (X)’ vs. window.Close() in closing handler
在WPF中,以下是关闭 Window $ c $的不同方法c>:
In WPF, here are different ways to close a Window
:
1) Window.Close()
2)选择从窗口系统菜单(左上)
关闭)3)单击窗口标题栏上的 X按钮(右上)
4)键盘快捷键:Alt + F4
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
所有这些操作都会触发WPF事件 Window.Closing
All of these actions trigger WPF event Window.Closing
如何区分这两种类型的操作?
How do I distinguish between these two types of actions?
在Excel / VBA中,这是可能的: VBA.VbQueryClose.vbFormCode
与 VBA.VbQueryClose.vbFormControlMenu
。
In Excel/VBA this is possible: VBA.VbQueryClose.vbFormCode
vs VBA.VbQueryClose.vbFormControlMenu
.
,说系统菜单操作将生成Windows事件 WM_CLOSE
。也许有一种方法可以从WPF中查看基础Windows事件。
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.
推荐答案
您可以调用HwndSource.AddHook来处理Win32消息,得到一个窗口的关闭原因。
类似于:
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);
};
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;
}
希望这会有所帮助。
这篇关于WPF:如何区分Window.Close()调用和系统菜单“关闭”操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!