八 关闭窗体 打开新窗体 二

37 阅读1分钟

image.png

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 TeacherDemo
{
  public partial class FrmMain : Form
  {
    public FrmMain()
    {
      InitializeComponent();
    }

    private void OpenNewForm(Form newFrm)
    {
      //【1】 关闭嵌入的其他窗体
      foreach (Control item in this.splitContainer.Panel2.Controls)
      {
        if (item is Form)
          ((Form)item).Close();
      }
      newFrm.TopLevel = false;  // 将子窗体设置成非顶级控件
      //newFrm.FormBorderStyle = FormBorderStyle.None; // 去掉子窗体的边框
      newFrm.Parent = this.splitContainer.Panel2; // 指定子窗体要嵌入的容器
      newFrm.Dock = DockStyle.Fill; // 保证子窗体会随着容器大小而变化
      newFrm.Show();
    }
    private void btnClose_Click(object sender, EventArgs e)
    {
      this.Close();
    }

    private void btnProductManage_Click(object sender, EventArgs e)
    {
      // [2] 打开新的窗体
      OpenNewForm(new FrmAddProduct());
      //FrmAddProduct newFrm = new FrmAddProduct();
      }
    }
  }