Access an existing main winform instance from any

2019-08-24 01:54发布

I am working a WinForm Application. I have a couple of forms on it. I want to be able to access my main form from any child form. I was able to do that through a custom button function and capture the Form_Closing event. I have one problem though which I'll explain below.

The code on the main form is as follow:

ChildForm form = new ChildForm(); // Create new Child Form instance
form.Show(); // Show Child form
this.Hide(); // Hide Main form

Using "this.Hide();" means that the main form still exists in memory and is still working, it's just hidden which is what I want.

The code on the child form

MainForm form = new MainForm(); // Create new Main Form instance
form.Show(); // Show Main Form
this.Close(); // Close Child Form

This is all well except on my second code block (Child Form directly above), the first line of code, creates a new instance of the main form. That is my problem, I don't want to create a new instance of that form, I want to show the already existing hidden instance (The main form I hid in the first block of code above).

I tried the following code on the Child form:

this.Parent.Show();

But I got this runtime error message: "System.NullReferenceException was unhandled: Message=Object reference not set to an instance of an object".

I understand what the error means, I just don't the code to create an object reference to that main form or how to reference it in any sort.

Any tips please?

Thanks ahead.

标签: c# winforms
2条回答
Luminary・发光体
2楼-- · 2019-08-24 02:30

You can make a constructor for your other forms that takes in a window as a parameter

private Form MyParent { get; set; }
public Form1(Form parent)
{
   MyParent = parent;
}

MyParent.Show();

where MyParent is a property of the form

you can call this via new ChildForm(this)


Edit

I just looked, not sure why I can't use a constructor for an IWin32Window but Show has an overload that takes one in which will set the Owner to a parent form

new ChildForm().Show(this);
ChildForm.Owner //returns MainForm (parent)
查看更多
【Aperson】
3楼-- · 2019-08-24 02:39

That should do it. Because these are single thread forms, the function will wait till you close the form before proceeding further.

ChildForm form = new ChildForm(); // Create new Child Form instance
this.Hide(); // Hide Main form
form.ShowDialog(); // Show Child form, wait for closing
this.Show();

You can also attach ChildForm closing event to function in MainForm.

public MainForm()
{
    ChildForm form = new ChildForm();
    form.FormClosed += OnClosed;  
}
public void OnClosed(object sender, EventArgs e)
{
     this.Show();
}
查看更多
登录 后发表回答