Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass in parent form to ShowDialog that is called from a class instance

I have a form.

In that form I create an instance of a class on a new thread because it runs some long running logic. The form also gives the user the ability to cancel this logic/thread.

That class opens a new form if input is required.

The new form sometimes appears behind the other form.

I set a property on the class:

public Form ParentForm{get;set;}

I can now do:

MyForm form = new MyForm();
form.ShowDialog(ParentForm);

However I get a cross thread exception when calling ShowDialog(ParentForm).

I know I can use InvokeRequired somehow but not sure how on a property.

Thanks

UPDATE: Have tried doing this but still get exception:

MyForm form = new MyForm();
form.ShowDialog(GetParentForm()); 



private Form GetParentForm()
{
    //You have to Invoke() so you can wait for the function to return and obtain its return value.
    if (ParentForm.InvokeRequired)
    {
        return (Form)ParentForm.Invoke(new Func<Form>(() => GetParentForm()));
    }
    else
    {
        return ParentForm;
    } 
}
like image 643
Jon Avatar asked Jun 19 '12 09:06

Jon


1 Answers

Your updated method (GetParentForm) won't work because you're wrapping the task of getting the reference to ParentForm in an InvokeRequired block. You could try wrapping the ShowDialog call in such a block instead, but I think you would still get the cross-threading error.

Your simplest fix would be to move the code that creates and shows the second form out of your class and into ParentForm. So instead of this:

MyForm form = new MyForm();
form.ShowDialog(ParentForm);

you would do this:

ParentForm.showMyNewForm();

and in ParentForm you would have this:

public void showMyNewForm()
{
    MyForm form = new MyForm();
    form.ShowDialog(this);
}

If MyForm needs to have a reference to the class on the other thread, you would just add a parameter to showMyNewForm() so that the reference to it can be passed in.

What you're trying to do here (creating and showing related, connected forms that are created on different threads) is really going against the grain of how forms are meant to be used in .NET.

like image 139
MusiGenesis Avatar answered Sep 27 '22 18:09

MusiGenesis