Go to the parent form in ShowDialog, which is called from an instance of the class

I have a form.

In this form, I create an instance of the class in a new thread because it starts some long logic. The form also gives the user the ability to cancel this logic / thread.

This class opens a new form if entry is required.

A new form sometimes appears after another form.

I set the property in the class:

public Form ParentForm{get;set;}

Now I can do:

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

However, when ShowDialog(ParentForm)I call, I get a cross-thread exception.

I know that I can use it somehow InvokeRequired, but I'm not sure how to use the property.

thank

UPDATE: tried to do this, but still get an 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;
    } 
}
+5
source share
2 answers

(GetParentForm) , ParentForm InvokeRequired. ShowDialog , , - .

ParentForm. :

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

:

ParentForm.showMyNewForm();

ParentForm :

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

MyForm , showMyNewForm(), .

, ( , , ), , .NET.

+1

async . :

public class MyForm : Form
{
    public void ShowModalAsync()
    {
        this.Invoke(new Action(()=> {
              ShowDilaog(..);
        }));  
    }
}

, :

MyForm form = new MyForm();
form.ShowModalAsync(...);

.

, , , Form.TopMost, true. , , , infront , infront .

0

All Articles