原文:通过WPF中UserControl内的按钮点击关闭父窗体
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37591671/article/details/79519298
通过WPF中UserControl内的按钮点击关闭父窗体
1.目的:
在设计界面的过程中,想通过UserControl内的一个按钮点击来关闭包含UserControl的父窗体,来展示其他的界面。
2.实现思路:
2.1我们知道在WPF中的UserControl,他本身是没有this.close事件的:
2.2能否找到UserControl的父容器来关闭
或许是我没找到,没有找到能关闭父容器的方法
3.实现方法:
最后通过Stack Overflow终于找到了可以实现该功能的方法:
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
private static extern IntPtr GetParent(IntPtr hWnd);
//I'd double check this constant, just in case
static uint WM_CLOSE = 0x10;
private void CloseContainingWindow(Visual visual)
{
// Find the containing HWND for the Visual in question
HwndSource wpfHandle = PresentationSource.FromVisual(this) as HwndSource;
if (wpfHandle == null)
{
throw new Exception("Could not find Window handle");
}
// Trace up the window chain, to find the ultimate parent
IntPtr hWindow = wpfHandle.Handle;
while (true)
{
IntPtr parentHWindow = GetParent(hWindow);
if (parentHWindow == (IntPtr)0) break;
hWindow = parentHWindow;
}
// Now send the containing window a close message
SendMessage(hWindow, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
}
将我们的UseControl传入到该方法:
4.参考链接
MFC-hosted WPF usercontrol how to close parent window on button press