-3

I have a windows application which has 2 forms. Iam trying to achieve this:

When the second form is displayed, I want the first form to be hidden.

I have tried like:

public Executor()
{
  InitializeComponent();
  Form1.ActiveForm.Hide();
}

But results in "cross-thread operation not valid control accessed from a thread other than the thread it was created on" before getting started the entire application.

How can I achieve what I said? Also in my later code I am trying to close as shown above with the code Form1.ActiveForm.Close();

Any ideas would be really appreciated..

huMpty duMpty
  • 14,346
  • 14
  • 60
  • 99
vysakh
  • 266
  • 2
  • 4
  • 19

2 Answers2

2

Use a delegate to invoke the Close method on the subject form's thread:

    private delegate void BlankDelegate();

    private void CloseForm()
    {
        if (this.InvokeRequired)
        {
            this.Invoke(new BlankDelegate(this.CloseForm));
        }
        else
        {
            this.Close();
        }
    }
Ashigore
  • 4,618
  • 1
  • 19
  • 39
0

You cannot access UI controls (or their parent form) from a thread other than the one running that form's UI thread

Try this-

 this.Invoke((Action)delegate { Form1.ActiveForm.Hide(); });
Microsoft DN
  • 9,706
  • 10
  • 51
  • 71