在按钮事件中泛化窗体调用
本文关键字:窗体 调用 泛化 按钮 事件 | 更新日期: 2023-09-27 18:26:36
每当单击按钮时,我通常会调用这段代码来显示表单。
private frmSelection _frmSelection;`
private void _frmSelection_FormClosing(object sender, FormClosingEventArgs e)
{
_frmSelection = null;
}
private void changeFeedOrderToolStripMenuItem_Click(object sender, EventArgs e)
{
if (_frmSelection == null)
{
_frmSelection = new frmSelection();
_frmSelection.FormClosing += _frmSelection_FormClosing;
_frmSelection.WindowState = FormWindowState.Minimized;
_frmSelection.Show();
_frmSelection.WindowState = FormWindowState.Normal;
}
else
{
_frmSelection.WindowState = FormWindowState.Minimized;
_frmSelection.WindowState = FormWindowState.Normal;
}
}
如果表单已打开,它将显示已打开的实例,而不是创建新实例。它运行良好
但我的问题是,每当我添加新表单时,我都需要复制粘贴并更改表单名称。
如何将其推广并添加到助手班
类似这样的东西:
public sealed class ReusableFormContainer<T> : IDisposable
where T : Form, new()
{
private bool isDisposed;
private void HandleFormClosing(object sender, FormClosingEventArgs e)
{
Form = null;
}
public T Form { get; private set; }
public void Show()
{
if (isDisposed)
{
throw new ObjectDisposedException(null);
}
if (Form == null)
{
Form = new T { WindowState = FormWindowState.Minimized };
Form.FormClosing += HandleFormClosing;
Form.Show();
}
else
{
Form.WindowState = FormWindowState.Minimized;
}
Form.WindowState = FormWindowState.Normal;
}
public void Dispose()
{
// IDisposable.Dispose is implemented to handle cases, when you want to close
// wrapped form using code
if (!isDisposed)
{
Form?.Dispose();
isDisposed = true;
}
}
}
用法:
// must be initialized somewhere in constructors
private readonly ReusableFormContainer<FormA> container_A;
private readonly ReusableFormContainer<FormB> container_B;
private void button1_Click(object sender, EventArgs e)
{
container_A.Show();
}
private void button2_Click(object sender, EventArgs e)
{
container_B.Show();
}
下面的代码可能会执行您想要的操作。只是考虑使用Application函数,因为这些函数可以覆盖线程上的所有表单。
public partial class Form1 : Form
{
public int i;
private Form1 _frmSelection;
public Form1()
{
InitializeComponent();
i = Application.OpenForms.Count;
}
private void _frmSelection_FormClosing(object sender, FormClosingEventArgs e)
{
_frmSelection = null;
}
private void button1_Click(object sender, EventArgs e)
{
if (_frmSelection == null)
{
_frmSelection = new Form1();
_frmSelection.FormClosing += _frmSelection_FormClosing;
_frmSelection.WindowState = FormWindowState.Minimized;
_frmSelection.WindowState = FormWindowState.Normal;
_frmSelection.Show();
if (Application.OpenForms.Count > 1)
{
_frmSelection.Text = Application.OpenForms[i].Text + " and going";
}
}
else
{
_frmSelection.WindowState = FormWindowState.Minimized;
_frmSelection.WindowState = FormWindowState.Normal;
}
}
}