C#----子窗体调用子窗体,但调用的子窗体仍属于父窗体

来源:互联网 发布:excel数据归类统计 编辑:程序博客网 时间:2024/05/16 15:22

在MDI编程中,从父窗体调用了子窗体,会出现子窗体隶属父窗体。但当我们要从一子窗体调用另一个子窗体,并且,调用过后,这个被子窗体调用出来的子窗体,会出现隶属于父窗体的情况是什么实现的呢?

下面是针对这种情况的一个简单实现。

 

在一个项目中建三个窗体,分别为Form1、Form2、Form3。其中,Form1设置为父窗体,在Form1上有一个按钮button1,在这个按钮的Click事件中,实现调用Form2。在Form2上也有一个按钮button1, 在这个按钮的Click事件中,实现调用Form3。

 

以下是具体的代码过程,代码中作了关键注释:

Form1中的代码:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

 

namespace MdiFormTest

{

    public partial class Form1 : Form

    {

        //定义一个Form1的static变量SForm1

        static public Form1 SForm1 = null;

        public Form1()

        {

            InitializeComponent();

 

            //把Form1赋给SForm1

            SForm1 = this;

        }

 

        private void button1_Click(object sender, EventArgs e)

        {

            Form2 form2 = new Form2();

            form2.MdiParent = this;

            form2.Show();

        }

    }

}

 

Form2中的代码:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

 

namespace MdiFormTest

{

    public partial class Form2 : Form

    {

        public Form2()

        {

            InitializeComponent();

        }

 

        private void button1_Click(object sender, EventArgs e)

        {

            Form3 form3 = new Form3();

            //指明Form3的父窗体是Form1

            form3.MdiParent = Form1.SForm1;

            form3.Show();

        }

    }

}

 

以上就是对这个问题的解决。