0

I'm working on a C# application.

I have an object used like a dialog box :

public partial class MyDialog : Form

The main windows is :

public class MyForm : Form

I can use it by :

public class ProgramApp
{
    public static MyForm MainForm { get { return _mainForm;  } }
}

In one function I can use both with :

MyDialog dlg = new MyDialog();
dlg.ShowDialog(ProgramApp.MainForm);

First call works good, but at the second one I have a System.InvalidOperationException with HResult = 0x80131509 and message :

Cross-thread operation not valid: Control 'MainForm' accessed from a thread other than the thread it was created on.

(translated from french, original message :)

"Opération inter-threads non valide : le contrôle 'MainForm' a fait l'objet d'un accès à partir d'un thread autre que celui sur lequel il a été créé."

What can I do to fix that ?

Edit :

I added this piece of code :

MyDialog dlg = new MyDialog();
bool needInvokeDlg = dlg.InvokeRequired;
bool needInvokeForm = ProgramApp.MainForm.InvokeRequired;
dlg.ShowDialog(ProgramApp.MainForm);

First attempt both are false. On second, needInvokeForm is true. How can I do an Invoke to set ProgramApp.MainForm as a parameter ?

A.Pissicat
  • 3,023
  • 4
  • 38
  • 93
  • 1
    did not find an answer on the original post – A.Pissicat Oct 18 '16 at 15:05
  • 1
    @dotctor Can you re-open the question please ? – A.Pissicat Oct 18 '16 at 15:14
  • 1
    Perhaps it would be enough to just cast the form to the required `IWin32Window` interface, i.e. `dlg.ShowDialog((IWin32Window)ProgramApp.MainForm);` as that doesn't have any UI element. – stuartd Oct 18 '16 at 15:23
  • 1
    I've tried but it doesn't work. The problem for me is to give the `MainForm` as parameter in another thread. I've try to invoke from `MainForm` and `dlg` but nothing works. I need help and my question has been closed (2 minutes after asking, I wonder if the closer read the question). Anyway i'll try an other way... – A.Pissicat Oct 18 '16 at 15:38

1 Answers1

1

The dialog needs to be invoked on the UI thread.

For a thorough discussion, see this post.

Community
  • 1
  • 1
Petter Hesselberg
  • 5,062
  • 2
  • 24
  • 42