FormClosing e.cancel = true无法正常工作 [英] FormClosing e.cancel = true not working

查看:268
本文介绍了FormClosing e.cancel = true无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#Windows应用程序.
我有我的主要GUI.当用户单击按钮时,我将启动一个新线程并打开一个新对话框(TestForm).

对话框表单包含以下代码:

C# windows application.
I have my main gui. When a user clicks a button I start a new thread and open a new dialog (TestForm).

the dialog form consists of this code:

private void TestForm_FormClosing(object sender, FormClosingEventArgs e)
{
    e.Cancel = true;
    this.Hide();
}




该线程仅包含




The thread only consists of

private static void startTestThread()
{
    test.ShowDialog();
    MessageBox.Show("Got Here");
}





测试定义如下:





where test is defined as follows:

public static TestForm test = new TestForm();



问题在于,当窗体关闭时,它确实会碰到关闭事件,并将e.cancel设置为true,但是随后对话框关闭,出现了显示此消息的MessageBox且线程死了.

我需要隐藏表格,然后继续执行线程.

谢谢:)



The problem is that when the form is closing, it does hit the closing event and set e.cancel to true, but then the dialog closes, MessageBox showing this comes up and the thread dies.

I need the form to just hide and the thread to continue.

Thanks :)

推荐答案

你为什么不

0)使用无模式形式(使用form.Show()代替form.ShowDialog())

1)删除允许用户关闭表单的"X"框

2)用自己创建的按钮处理隐藏的东西

这样更容易,并且表单总是可用的(我想线程以某种方式对其进行更新).
Why don''t you

0) use a modeless form (use form.Show() instead of form.ShowDialog())

1) remove the "X" box that allows the user to close the form

2) Handle your hide stuff in a button of your own creation

It''s much easier that way, and the form is always available (I suppose for the thread to update it in some way).


您的根本问题是不同的.您应该只在UI线程中做所有UI事情.

当然,您可以使用线程,并使用其他线程来更新/修改/使控件无效,但是您需要使用Control.InvokeRequiredControl.Invoke.实际上,当您执行此操作时,作为参数Control.Invoke传递的委托将被放置在UI队列中,并且无论如何实际上将在UI线程中调用.

您是否(有机会)认为在单独的线程中创建表单/对话框会使并行处理不同的表单?如果是这样,请三思:您甚至可以在一个UI线程中使它们独立工作-这称为面向事件的设计.

好吧,最肯定的是,您不应该在非UI线程中创建表单/对话框.即使想到后果,也很可怕:-).

-SA
You root problem is different. You should do all your UI stuff in UI thread only.

You can use threads, of course and update/modify/invalidate your controls be your other thread, but you need to use Control.InvokeRequired and Control.Invoke. In fact, when you do this, a delegate passed as a parameter of Control.Invoke will be put in UI queue and actually called in UI thread anyway.

Did you — by any chance — think that creation a form/dialog in a separate thread would make working different forms in parallel? If so, think again: you can have them working independently even in one UI thread — this is called event-oriented design.

Well, most certainly, you should not create a form/dialog in your non-UI thread. It''s scary even to think about the consequences :-).

—SA


此线程 [ ^ ]似乎已经解决了类似的问题. (您必须滚动浏览所有广告才能看到答案).
This thread[^] seems to have solved a similar problem. (You will have to scroll past all the ads to see the answers).


这篇关于FormClosing e.cancel = true无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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