请问:winform的父窗体中怎样判断子窗是否存在

2024-12-13 09:19:11
推荐回答(3个)
回答1:

这就是经典的“单利模式”,解决方法早有人总结出来了,给你举个详细的例子:
两个窗体:父窗体(ParentForm)子窗体(ChildForm),点击父窗体中的按钮只弹出一个弹出子窗体
1.修改子窗体代码
1.1将子窗体的构造函数改为Private(这样就不能随便去new了)
private ChildForm()
{
InitializeComponent();
}
1.2在子窗体中添加一个静态的私有变量,类型就是子窗体类型
private static ChildForm childFromInstanc;
1.3构建该私有静态字段childFromInstanc的静态属性ChildFromInstanc(用来控制 childFromInstanc字段的值)
public static ChildForm ChildFromInstanc
{
get
{
if (childFromInstanc == null || childFromInstanc.IsDisposed)
//判断childFromInstanc是否有值,不为null或者窗体释放(当你将子窗体关了的时候)为childFromInstanc赋值
{
childFromInstanc = new ChildForm();
}
return childFromInstanc;
//返回的childFromInstanc(子窗体存在时返回的是null,关闭了(IsDisposed为true)或者第一次打开子窗体返回一个ChildForm实例)
}
}
2.在父窗体中调用
按钮的单击事件添加下面代码:
private void btnShowChildForm_Click(object sender, EventArgs e)
{
//调用子窗体的静态字段(该静态字段就是一个子窗体实例)
ChildForm cf = ChildForm.ChildFromInstanc;
if (cf != null)
{
cf.Show();//显示子窗体
}
}

完整代码:
子窗体
public partial class ChildForm : Form
{
private ChildForm()
{
InitializeComponent();
}
private static ChildForm childFromInstanc;
public static ChildForm ChildFromInstanc
{
get
{
if (childFromInstanc == null || childFromInstanc.IsDisposed)
//判断childFromInstanc是否有值,不为null或者窗体释放(当你将子窗体关了的时候)为childFromInstanc赋值
{
childFromInstanc = new ChildForm();
}
return childFromInstanc;
//返回的childFromInstanc(子窗体存在时返回的是null,关闭了(IsDisposed为true)或者第一次打开子窗体返回一个ChildForm实例)
}
}
}
父窗体:
private void btnShowChildForm_Click(object sender, EventArgs e)
{
//调用子窗体的静态字段(该静态字段就是一个子窗体实例)
ChildForm cf = ChildForm.ChildFromInstanc;
if (cf != null)
{
cf.Show();//显示子窗体
}
}

说的够详细了吧?嘿嘿

回答2:

父窗体定义一个成员变量~判断是否为NUll或在不为NUll的情况下是否Disposed

回答3:

C# code

private void button9_Click(object sender, EventArgs e)
{
Form1 singleForm = null;//初始化为空
foreach (Form item in Application.OpenForms)
{
if (item is Form1)
{
singleForm = item;
break;
}
}
if (singleForm == null) singleForm = new Form1();
singleForm.Show();
}