欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

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

时间:2021-06-19 08:16:37|栏目:.NET代码|点击:

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
}

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

上一篇:C#调用Rar文件及获取Rar返回值的方法

栏    目:.NET代码

下一篇:实例讲解动态加载gridview中的行及其样式

本文标题:C#设置MDI子窗体只能弹出一个的方法

本文地址:http://www.codeinn.net/misctech/144394.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有