ouzining

 

c#winform窗体嵌入

最近开发项目,错误的理解了需求,自己做了个窗体的嵌套,虽然是错误的理解了,但是功能还是实现了,做下标记,需要时可以拿来看看。

新建两个窗体Form1和Form2,现在需要将Form2显示到Form1里,我们该怎么办呢?上代码先,一看就明白了,在form 的load方法里加入下面的代码,form2是要显示的子窗体,

 

namespace chuangtiqiantao
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Form2 f = new Form2( );
            this.IsMdiContainer = true;//指定为父窗体
            f.MdiParent = this;//指定子窗体的父窗体
            f.Parent = this.splitContainer1.Panel1;//指定父容器
            f.Show();
        }
    }
}

 

这些代码得意思已注明,运行效果如下

 image.axd (1158×607)

到此,嵌入成功,这是基本的嵌入办法,更多的时候我们需要对嵌入进去的窗体做操作,比如说form2的内容很多,我想放大里面的子窗体form2去做一些操作,也就是将form2跳出form1的束缚,等操作完了再回到form1中,下面是具体的代码和思路,首先将from1设计器里的容器panle设为公有(public)  public System.Windows.Forms.SplitContainer splitContainer1,这样子子窗体才能访问到,form1的load函数如下,只是加了一个参数this

 

namespace chuangtiqiantao
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Form2 f = new Form2(this);
            this.IsMdiContainer = true;//指定为父窗体
            f.MdiParent = this;//指定子窗体的父窗体
            f.Parent = this.splitContainer1.Panel1;//指定父容器
            f.Show();
        }
    }
}

 

现在得去form2里面做操作了上代码

 

namespace chuangtiqiantao
{
    public partial class Form2 : Form
    {
        Form1 f1 = null;
        public Form2(Form1 f)
        {
            InitializeComponent();
            f1 = f;
        }

        private void Form2_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Maximized)
            {
                this.MdiParent = null;//不设父窗体
            }
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.MdiParent = f1;//指定子窗体的父窗体
                this.Parent = f1.splitContainer1.Panel1;//指定父容器
            }
        }
    }
}

 

运行效果是,点击最大化的时候form2跳出form1的容器限制范围,点击最小化的时候form2回到form1中,具体结果图片我就不上传了。

posted on 2014-05-27 18:13  ouzining  阅读(1618)  评论(0编辑  收藏  举报

导航