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()函数,将其禁用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
WPF中,当窗口关闭时,如果需要处理主界面中与窗口调用的控件相关的操作,你可以使用以下方法: 1. 在主界面中创建一个事件处理程序,在该处理程序中可以执行需要的操作。例如,在主窗口的代码中定义一个名为"ChildWindowClosed"的事件: ```csharp public partial class MainWindow : Window { public event EventHandler ChildWindowClosed; // 主窗口的其他代码... private void OnChildWindowClosed() { ChildWindowClosed?.Invoke(this, EventArgs.Empty); } } ``` 2. 在窗口的代码中,当窗口关闭时,触发主界面的事件处理程序。可以通过在窗口的Closing事件中调用主界面的事件处理程序来实现。例如,在窗口的代码中添加以下代码: ```csharp public partial class ChildWindow : Window { private MainWindow mainWindow; public ChildWindow(MainWindow mainWindow) { InitializeComponent(); this.mainWindow = mainWindow; // 窗口的其他代码... } private void ChildWindow_Closing(object sender, CancelEventArgs e) { mainWindow.OnChildWindowClosed(); } // 窗口的其他代码... } ``` 3. 在主界面的代码中,订阅ChildWindowClosed事件,并在事件处理程序中执行所需的操作。例如,在主窗口的代码中添加以下代码: ```csharp public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); // 订阅ChildWindowClosed事件 ChildWindowClosed += MainWindow_ChildWindowClosed; // 主窗口的其他代码... } private void MainWindow_ChildWindowClosed(object sender, EventArgs e) { // 执行与窗口关闭相关的操作 // 例如,重新加载数据或更新界面等 } } ``` 通过以上步骤,你可以在窗口关闭时处理主界面中与窗口调用的控件相关的操作。请注意,这只是一种可能的实现方式,具体的实现取决于你的需求和代码结构。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值