在 Tabcontrol 上关闭标签页时,调用 form.close

When closing a tabpage on a Tabcontrol, call form.close

在我的应用程序中,我试图在标签页中使用表单。这些表格都是数据管理表格。 我编辑了 tabcontrol(创建了一个自定义 tabcontrol)所以我可以通过双击 tabheader 来删除标签页。

protected override void OnMouseDoubleClick(MouseEventArgs e)
{
  base.OnMouseDoubleClick(e);
  //* Default method of closing a tab.
  if (Selectedtab != null)
    TabPages.Remove(Selectedtab);
}

虽然有效。它实际上没有做我需要的。 因为标签页中表单的任何更改都将丢失,无论下面

public partial class SomeForm : Form
{
  private void SomeForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (HasChanges() && CustomMessage.WarningBox("There is unsaved data. Are you sure you want to close"))
            return;
        ((TabControl)((TabPage)this.Parent).Parent).TabPages.Remove((TabPage)this.Parent);
    }
}

在此函数设置断点时,一直不进入。
现在我的问题是:是否可以从Tabcontrol调用窗体的Close方法。最好像下面这样。

protected override void OnMouseDoubleClick(MouseEventArgs e)
{
  base.OnMouseDoubleClick(e);
  if (Selectedtab != null)
  {
    if (Selectedtab.EmbeddedForm != null)
      TabPages.ASelectedtab.EmbeddedForm.Close();
  }
}

我面临的主要问题是我不知道如何通过只知道选定的选项卡来访问表单上的功能。我也找不到。


以KyleWang的答案为基础后的解决方案: 自定义控件:

protected override void OnMouseDoubleClick(MouseEventArgs e)
{
  base.OnMouseDoubleClick(e);
  string frmSearchName = "Frm" + SelectedTab.Name.Substring(3);
  Form f = (Form)Application.OpenForms[frmSearchName];
  if (f != null)
    f.Close();
  else
    TabPages.Remove(SelectedTab);
}

表格:

private void SomeForm_FormClosing(object sender, FormClosingEventArgs e)
{
  SetChanges();
  if (HasChanges() && !CustomMessage.WarningBox("There is unsaved data. Are you sure you want to close?"))
    e.Cancel = true;
  else
    ((TabControl)((TabPage)this.Parent).Parent).TabPages.Remove((TabPage)this.Parent);
}    

您可以使用属性 Application.OpenForms获取打开的表单实例。

private void Form1_Load(object sender, EventArgs e)
{
    tabControl1.TabPages.Clear();
    PageForm1 f1 = new PageForm1();
    AddNewTab(f1);
}

private void AddNewTab(Form frm)
{
    TabPage tab = new TabPage(frm.Text);
    frm.TopLevel = false;
    frm.Parent = tab;
    frm.Visible = true;
    tabControl1.TabPages.Add(tab);
    frm.Location = new Point((tab.Width - frm.Width) / 2, (tab.Height - frm.Height) / 2);
    tabControl1.SelectedTab = tab;
}

private void tabControl1_DoubleClick(object sender, EventArgs e)
{
    Form f = (Form)Application.OpenForms[tabControl1.SelectedTab.Text];
    f.Close();
    tabControl1.TabPages.RemoveAt(tabControl1.SelectedIndex);
}