当前位置: 移动技术网 > IT编程>开发语言>c# > C#设置MDI子窗体只能弹出一个的方法

C#设置MDI子窗体只能弹出一个的方法

2019年07月18日  | 移动技术网IT编程  | 我要评论

windows程序设计中的mdi(multiple document interface)官方解释就是所谓的多文档界面,与此对应就有单文档界面 (sdi), 它是微软公司从windows 2.0下的microsoft excel电子表格程序开始引入的,excel电子表格用户有时需要同时操作多份表格,mdi正好为这种操作多表格提供了很大的方便,于是就产生了mdi程序。

新建一个windowform程序。得到一个窗体作为我们父窗体parent。拖入一个menustrip空间。在新建一个窗体frmchildren作为我们子窗体,界面如下图所示:

其代码如下所示:

public form1()
{
  initializecomponent();
  //将form1设置为mdi窗体,当然在form1的ismdicontainer属性页可以设置
  this.ismdicontainer = true;
}

在menustrip打开子窗体的事件代码如下:

private void tsmiopenwindow_click(object sender, eventargs e)
{  
  frmchildren child = frmchildren.getwindow();//调用方法
  child.mdiparent = this;//设置child的父窗体为当前窗体
  child.show();
  
}

getwindow()这个方法在哪里呢。当然是在frmchildren子窗体里面写

 public partial class frmchildren : form
  {
    private frmchildren() //由 public frmchildren改为 private frmchildren
    {
      initializecomponent();
    }
    static frmchildren fc = null; 创建一个静态对象
    public static frmchildren getwindow()
    {  //当子窗体没有开启或者已经释放。就可以创建新窗体
      if (fc==null||fc.isdisposed)
      {
        fc = new frmchildren();
      }
      return fc;
    }
  }

第二种方法:

这种方法个人觉得很简单。直接在在menustrip打开子窗体的事件下面写就ok了

private void tsmiopenwindow_click(object sender, eventargs e)
{ 

#region 方法二application收集打开的窗体,用索引器来寻找,就是窗体的name属性
//方法二.如果没有name为frmchildren的子船体,实例化创建。和之前的正规做法没有什么差别,只是多了判断。
if (application.openforms["frmchildren"] == null)
{
frmchildren child = new frmchildren();
child.mdiparent = this;
child.show();
}
else//有name为frmchildren的子船体,就直接show()
{
application.openforms["frmchildren"].show();
}
#endregion
}

感兴趣的朋友可以调试运行一下本文所述示例,相信会有不小的收获。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网