A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 陈君 金牌黑马   /  2014-9-9 22:30  /  951 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

这篇文章主要介绍了C#设置MDI子窗体只能弹出一个的方法,很实用的技巧,需要的朋友可以参考下
Windows程序设计中的MDI(Multiple Document Interface)官方解释就是所谓的多文档界面,与此对应就有单文档界面 (SDI), 它是微软公司从Windows 2.0下的Microsoft Excel电子表格程序开始引入的,Excel电子表格用户有时需要同时操作多份表格,MDI正好为这种操作多表格提供了很大的方便,于是就产生了MDI程序。
新建一个WindowForm程序。得到一个窗体作为我们父窗体Parent。拖入一个menustrip空间。在新建一个窗体FrmChildren作为我们子窗体,界面如下图所示: 其代码如下所示:
  1. public Form1()
  2. {
  3. InitializeComponent();
  4. //将Form1设置为MDI窗体,当然在Form1的IsMdiContainer属性页可以设置
  5. this.IsMdiContainer = true;
  6. }
复制代码

在menustrip打开子窗体的事件代码如下:
  1. private void tsmiOpenWindow_Click(object sender, EventArgs e)
  2. {
  3. FrmChildren child = FrmChildren.GetWindow();//调用方法
  4. child.MdiParent = this;//设置child的父窗体为当前窗体
  5. child.Show();

  6. }
复制代码

GetWindow()这个方法在哪里呢。当然是在FrmChildren子窗体里面写
  1. public partial class FrmChildren : Form
  2. {
  3. private FrmChildren() //由 public FrmChildren改为 private FrmChildren
  4. {
  5. InitializeComponent();
  6. }
  7. static FrmChildren fc = null; 创建一个静态对象
  8. public static FrmChildren GetWindow()
  9. { //当子窗体没有开启或者已经释放。就可以创建新窗体
  10. if (fc==null||fc.IsDisposed)
  11. {
  12. fc = new FrmChildren();
  13. }
  14. return fc;
  15. }
  16. }
复制代码

第二种方法:
这种方法个人觉得很简单。直接在在menustrip打开子窗体的事件下面写就ok了
  1. private void tsmiOpenWindow_Click(object sender, EventArgs e)
  2. {

  3. #region 方法二Application收集打开的窗体,用索引器来寻找,就是窗体的Name属性
  4. //方法二.如果没有Name为FrmChildren的子船体,实例化创建。和之前的正规做法没有什么差别,只是多了判断。
  5. if (Application.OpenForms["FrmChildren"] == null)
  6. {
  7. FrmChildren child = new FrmChildren();
  8. child.MdiParent = this;
  9. child.Show();
  10. }
  11. else//有Name为FrmChildren的子船体,就直接show()
  12. {
  13. Application.OpenForms["FrmChildren"].Show();
  14. }
  15. #endregion
  16. }
复制代码


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马