WPF不让子窗口关闭的做法

在WPF编程中,可能需要去除窗口的右上角的几个按钮:最大化按钮、最小化按钮和关闭按钮,其他几个都很好处理,就是这个关闭按钮,WPF模型不提供删除或隐藏功能,我们只有采用一些非正常手段,比如使用Win32函数,比如禁用,对于禁用关闭功能,可以重载OnClosing()函数来实现,——使用户无法通过点击右上角的关闭按钮来关闭窗口:


        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true; 
        } 

另一种方法就比较麻烦了,但是也是最彻底的方法:去除关闭按钮

 首先,在你的Window 类中申明:


private const int GWL_STYLE = -16;
private const int WS_SYSMENU = 0x80000;
[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);

 然后,在装载事件中加入:


var hwnd = new WindowInteropHelper(this).Handle;
SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU);

 但是这种情况下用户仍然可以通过Alt+F4关闭窗口,所以你可能仍然需要实现上面所说的重载OnClosing()函数,将其禁用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值