通过WPF中UserControl内的按钮点击关闭父窗体

原文: 通过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

posted on 2019-02-15 10:51 NET未来之路 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/lonelyxmas/p/10382327.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值