阻止父窗体关闭 [英] Stop a parent form from closing

查看:23
本文介绍了阻止父窗体关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 winforms 应用程序,我需要一个很好的方法来处理以下问题..

I have a winforms application and I need a good way to handle the following..

基本上,我有主申请表,其中还有子申请表.

Basically, I have the main application form, and within that, I have child forms.

用户可以在父表单上点击关闭".但是在儿童形态中,可能会发生一些事情.例如,我可能编辑了一些数据绑定字段.

The user can hit 'close' on the parent form. But within the child form, some things might be happening. For instance, I may have edited some databound fields.

我目前捕捉到孩子的关闭,并正确保存任何更改.

I currently catch the close within the child, and correctly save any changes.

但是,现在我想要取消关闭的选项.所以子表单会提示用户,他们实际上可以取消关闭的应用程序.

However, now I want the option to cancel the close. So the child form would prompt the user, and they could actually cancel the application from closing.

我在子窗体关闭事件中尝试了 e.Cancel,但这不起作用 - 我假设是因为父窗体仍在关闭...有没有办法从子窗体中取消父窗体的关闭过程...?

I tried e.Cancel within the child form closing event, but this isn't working- I'm assuming because the parent is still closing... Is there a way to cancel the parent form's closing process from within the child...?

推荐答案

我建议在主表单中订阅 FormClosing 事件并验证每个子表单的状态并防止表单关闭(如果需要).下面的代码可能会对您有所帮助,并提供详细的信息.

I suggest subscribing for FormClosing event in main form and validating states for each child form and prevent form close (if required). Below code might help you and give fair idea of details.

private void Main_FormClosing( object sender, FormClosingEventArgs e ) 
{
    foreach(var f in childforms)
    {
        if(!f.CanClose())
        {
            e.Cancel = true;
            return;
        }
    }

    e.Cancel = false;   
}

这篇关于阻止父窗体关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆