FormClosing 委托无法与 ShowDialog() 方法一起使用

发布于 2024-11-05 11:29:19 字数 313 浏览 0 评论 0 原文

在我的 C# WinForms 程序中,我有一些表单,我将其中一个显示为对话框:

MyForm mf = new MyForm();
mf.ShowDialog();

但是当我尝试为它们分配表单关闭事件时,它不起作用;

mf.FormClosing += delegate { MessageBox.Show("Dialog is closed.")};

问题是什么?

PS:当我使用 mf.Show() 方法调用表单时,它工作正常。

谢谢。

In my C# WinForms program I have some forms and I show one of them as a dialog:

MyForm mf = new MyForm();
mf.ShowDialog();

But when I try to assigne a form closing event for them, it is not working;

mf.FormClosing += delegate { MessageBox.Show("Dialog is closed.")};

What is the problem?

P.S: It works fine when I call the form using mf.Show() method.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

大姐,你呐 2024-11-12 11:29:19

“不工作”是极其含糊的。您的代码片段中缺少一个分号。不得不猜测,不要在调用 ShowDialog() 之后分配 FormClosing 事件,那样就太晚了。这工作正常:

    private void button1_Click(object sender, EventArgs e) {
        using (var mf = new Form2()) {
            mf.FormClosing += delegate { MessageBox.Show("Dialog is closed."); };
            mf.ShowDialog();
        }
    }

"Not working" is hopelessly ambiguous. There's a semi-colon missing in your snippet. Having to guess, don't assign the FormClosing event after calling ShowDialog(), that's too late. This works fine:

    private void button1_Click(object sender, EventArgs e) {
        using (var mf = new Form2()) {
            mf.FormClosing += delegate { MessageBox.Show("Dialog is closed."); };
            mf.ShowDialog();
        }
    }
那支青花 2024-11-12 11:29:19

你使用的顺序是什么?首先你必须注册事件,然后调用 mf.ShowDialog()。

MyForm mf = new MyForm();
mf.FormClosing += delegate { MessageBox.Show("Dialog is closed.")};
mf.ShowDialog();

您在 MessageBox 中写入“对话框已关闭”,但您注册到 FormClosing。请注意,有一个 FormClosed 和一个 FormClosing 事件。这是不同的事件。

What is the sequence you use? First you have to register the event, then call mf.ShowDialog().

MyForm mf = new MyForm();
mf.FormClosing += delegate { MessageBox.Show("Dialog is closed.")};
mf.ShowDialog();

You write in the MessageBox "Dialog is closed", but you register to FormClosing. Please note, that there is a FormClosed and a FormClosing-event. This are different events.

回眸一笑 2024-11-12 11:29:19

作为测试,尝试将 ShowDialog 更改为 Show。行为(事件如何触发)确实不同。您可能需要显式调用 dispose 方法。

http://www.dotnetmonster.com/Uwe/Forum.aspx/dotnet-vb/56720/If-I-want-FormClosing-and-FormClose-to-run-am-I-suppose-呼叫

As a test, try changing ShowDialog to Show. The behavior (how events are fired) is indeed different. You may need to call the dispose method explicitly.

http://www.dotnetmonster.com/Uwe/Forum.aspx/dotnet-vb/56720/If-I-want-FormClosing-and-FormClose-to-run-am-I-suppose-to-call

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文