委托-嵌入窗体练习

实现效果:

1,添加一个Panel

2,建三个窗体

 FormMain代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 嵌入窗体应用
{
    //声明委托
    public delegate void ShowForm(Form form);
    public partial class FormMain : Form
    {      
        public FormMain()
        {
            InitializeComponent();
        }
        
        public void ShowFormMethod(Form form)
        {
            //判断Panel中有没有窗体,有就关掉
            foreach (var item in panel1.Controls)
            {
                if (item is Form)
                {
                  Form a=  item as Form;
                    a.Close();
                }
            }
            form.TopLevel = false;
            this.panel1.Controls.Add(form);
            form.Show();
            //判断是不是1#子窗体
            if (form is FormSon)
            {
                FormSon formSon = form as FormSon;
                formSon.showForm = this.ShowFormMethod;
            }
            //判断是不是2#子窗体
            if (form is FormChild)
            {
                FormChild formChild = form as FormChild;
                formChild.showForm = this.ShowFormMethod;
            }
        
        }
        //1#
        private void button1_Click(object sender, EventArgs e)
        {
            ShowFormMethod(new FormSon());
        }
        //2#
        private void button2_Click(object sender, EventArgs e)
        {
            ShowFormMethod(new FormChild());
        }
    }
}
View Code

FormChild代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 嵌入窗体应用
{
    public partial class FormChild : Form
    {
        public FormChild()
        {
            InitializeComponent();
        }
        //定义委托变量
        public ShowForm showForm;
        private void button1_Click(object sender, EventArgs e)
        {
            showForm(new FormSon());
        }
    }
}
View Code

FormSom代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 嵌入窗体应用
{
    public partial class FormSon : Form
    {
        public FormSon()
        {
            InitializeComponent();
        }
        //定义委托变量
        public ShowForm showForm;
        private void button1_Click(object sender, EventArgs e)
        {
            showForm(new FormChild());
        }
    }
}
View Code
原文地址:https://www.cnblogs.com/Luck1996/p/11986223.html