C# Form of a form is on separate thread

China☆狼群 提交于 2021-02-10 15:51:55

问题


I have strange problem.

I have 3 forms. form1, form2, form3.

form1 is starting/main form. in form1 I have code:

form2 f2 = new form2;
f2.ShowDialog();

form2 opens, I can't focus on foorm1, they are both on the same thread. Just what I want.

On form2 I have code:

form3 f3 = new form3;
DialogResult result = f3.ShowDialog();

I run this code and... For some, unknown for me reason this form3 runs on new thread and I can focus on form2. I don't want this to happen. I have no idea why this form3 runs on new thread. I can't use DialogResult because it leads to error (Cross-thread).

It behaves as if I was using f3.Show() but I'm using f3.ShowDialog();

Than you in advance.

P.S.

If i use

form3 f3 = new form3;
DialogResult result = f3.ShowDialog(this);

I got this:

System.InvalidOperationException was unhandled by user code
Message=Cross-thread operation not valid: Control 'form2' accessed from a thread other than the thread it was created on.

on this line:

DialogResult result = f3.ShowDialog(this);

回答1:


Dialogs function by implementing their own message loop. Since both threads have a message loop processing messages, you have two dialogs enabled. Either manually disable the first dialog or create and show all dialogs from the same thread. I would strongly recommend that you do all the UI in a single thread. Please see the InvokeRequired and Invoke members of Control.



来源:https://stackoverflow.com/questions/4576623/c-sharp-form-of-a-form-is-on-separate-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!