Hooch
Hooch

Reputation: 29673

C# Form of a form is on separate thread

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);

Upvotes: 1

Views: 875

Answers (1)

Dark Falcon
Dark Falcon

Reputation: 44181

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.

Upvotes: 3

Related Questions