隐藏表单,然后再次显示相同的表单

本文关键字:表单 显示 然后 隐藏 | 更新日期: 2023-09-27 17:51:09

当用户单击'X'时,我需要隐藏ticketForm。当单击"X"时,窗体将被隐藏。隐藏后,用户拥有menuForm。这个表单包含一个按钮,当按下时,它应该重新打开ticketForm与文本框内相同的文本(而不是一个全新的表单)。

我怎么能"显示"的形式,我正在工作,而不是弹出一个窗体与新的文本框?

这是按钮的代码:

private void btnTickets_Click(object sender, EventArgs e)
    {
        ticketForm tF = (ticketForm)Application.OpenForms["ticketForm"];

  if (tF != null)
    {
        MessageBox.Show("Ticket is already open!");
    }
    else
    {
        tF.ShowDialog();
    }
}

这是ticketForm Closing EventHandler的代码

 private void ticketForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (MessageBox.Show("You may continue editing the ticket later by clicking 'ticket' at the menu", "", MessageBoxButtons.OK, MessageBoxIcon.Stop) == DialogResult.OK)
            {
               menuForm mF = (menuForm)Application.OpenForms["menuForm"];
               if (mF != null)
                {
                    this.Hide();
                    mF.btnTickets.Enabled = true;
                }
            }
        else
        {
            e.Cancel = true;
        }
    }

谢谢

隐藏表单,然后再次显示相同的表单

试试下面的两个表单代码

形式1

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        Form2 form2;
        public Form1()
        {
            InitializeComponent();
            form2 = new Form2(this);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            form2.Show();
            string  results = form2.GetData();
        }
    }
}
​
从2

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        Form1 form1;
        public Form2(Form1 nform1)
        {
            InitializeComponent();
            this.FormClosing +=  new FormClosingEventHandler(Form2_FormClosing);
            form1 = nform1;
            form1.Hide();
        }
        private void Form2_FormClosing(object sender, FormClosingEventArgs e)
        {
            //stops form from closing
            e.Cancel = true;
            this.Hide();
        }
        public string GetData()
        {
            return "The quick brown fox jumped over the lazy dog";
        }
    }
}
​

我不确定你实际上在哪里创建你的票形式,但你的代码来检查它是否可见是不会工作的。检查它是否为空并不意味着它实际上是可见的。要检查它是否确实可见,你需要类似这样的代码:

if (tF != null && !tF.IsDisposed)
{
    if (tF.Visible)
        MessageBox.Show("Ticket is already open!")
    else
        tF.ShowDialog();
}
else
{
    //recreate your dialog
}

话虽如此,我将避免依赖于OpenForms属性,而宁愿管理实例与私有成员的某个地方-也许在menuForm。