InvalidOperationException on ShowDialog
<p>I'm working on a C# application. </p>

<p>I have an object used like a dialog box :</p>

<pre><code>public partial class MyDialog : Form
</code></pre>

<p>The main windows is :</p>

<pre><code>public class MyForm : Form
</code></pre>

<p>I can use it by :</p>

<pre><code>public class ProgramApp
{
    public static MyForm MainForm { get { return _mainForm;  } }
}
</code></pre>

<p>In one function I can use both with :</p>

<pre><code>MyDialog dlg = new MyDialog();
dlg.ShowDialog(ProgramApp.MainForm);
</code></pre>

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

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

<p>(translated from french, original message :)</p>

<blockquote>
  <p>"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éé."</p>
</blockquote>

<p>What can I do to fix that ?</p>

<p>Edit :</p>

<p>I added this piece of code :</p>

<pre><code>MyDialog dlg = new MyDialog();
bool needInvokeDlg = dlg.InvokeRequired;
bool needInvokeForm = ProgramApp.MainForm.InvokeRequired;
dlg.ShowDialog(ProgramApp.MainForm);
</code></pre>

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