从任何子窗体访问现有的主 winform 实例 [英] Access an existing main winform instance from any child form

查看:22
本文介绍了从任何子窗体访问现有的主 winform 实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 WinForm 应用程序.我有几个表格.我希望能够从任何子表单访问我的主表单.我能够通过自定义按钮功能来做到这一点并捕获 Form_Closing 事件.我有一个问题,但我将在下面解释.

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.

主窗体上的代码如下:

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

使用this.Hide();"意味着主窗体仍然存在于内存中并且仍在工作,它只是隐藏了我想要的.

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.

子窗体上的代码

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();

但我收到此运行时错误消息:System.NullReferenceException 未处理:Message=未将对象引用设置为对象的实例".

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.

请问有什么建议吗?

先谢谢了.

推荐答案

应该这样做.因为这些是单线程表单,该函数会等到您关闭表单再继续.

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();

您还可以将 ChildForm 关闭事件附加到 MainForm 中的函数.

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();
}

这篇关于从任何子窗体访问现有的主 winform 实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆