这个问题在这里已有答案:
首先,我想澄清类似的问题,已经在stackoverflow中被问到,但没有一个解决了我的问题。因此,在将我的问题标记为重复之前,请先了解我的问题。
我有两个form
名为frmNewCustomer
和frmCustomers
。在frmCustomers
内部,我有一个名为button
的btnNewCustomer
控件,每当我点击frmNewCustomer
时打开button
。这两种形式是另一种形式的MdiChildren
,名为WMS
。现在,如果它已经打开,我不想打开form
。为此我所做的就是这个(frmCustomers
的代码)。
namespace WMS.Presentation
{
public partial class frmCustomers : Form
{
Form newCustomer = new frmNewCustomer();
public frmCustomers()
{
InitializeComponent();
}
private void btnNewCustomer_Click(object sender, EventArgs e)
{
if (newCustomer.IsDisposed)
newCustomer = new frmNewCustomer();
newCustomer.MdiParent = this.MdiParent;
newCustomer.Show();
newCustomer.BringToFront();
}
}
}
现在假设,我从主要的frmCustomers
菜单中打开了form (Form1)
表单。之后我点击按钮btnNewCustomer
。所以,我必须在form
内开启Form1
。如果我再次点击Form1
的文件菜单并尝试打开frmCustomers
它不会打开一个新的表单,它只是focus
在打开的frmCustomers
实例上很好。这样我就可以在focus
上frmNewCustomers
了。
现在,如果我关闭frmCustomers
而frmNewCustomer
打开然后再次打开frmCustomers
并尝试focus
在打开的frmNewCustomers
点击btnNewCustomer
它不起作用。它打开了一个我不想要的新frmNewCustomer
。我只是想专注于frmNewCustomer
的打开实例。我该怎么做才能解决我的问题?我附上a截图,以便您可以更好地了解我的问题。
尝试这个关闭newCustomer
形式,同时关闭frmCustomers
形式。
namespace WMS.Presentation
{
public partial class frmCustomers : Form
{
Form newCustomer = new frmNewCustomer();
public frmCustomers()
{
InitializeComponent();
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(FormClosing);
}
private void btnNewCustomer_Click(object sender, EventArgs e)
{
if (newCustomer.IsDisposed)
newCustomer = new frmNewCustomer();
newCustomer.MdiParent = this.MdiParent;
newCustomer.Show();
newCustomer.BringToFront();
}
private void FormClosing(object sender, EventArgs e)
{
if (!newCustomer.IsDisposed)
newCustomer.Close();
}
}
}
注意:写在SO上。没试过。请进行必要的更改。
有许多主动和反应的方式来做到这一点
但是,你可以使用这样的东西,这将重新激活Form
,如果它打开,或创建它,如果它没有。
public void OpenExclusive<T>(Form parent) where T : Form, new()
{
foreach (Form form in Application.OpenForms)
{
if (form.GetType() == typeof(T))
{
form.Activate();
return;
}
}
Form newForm = new T();
newForm.MdiParent = parent;
newForm.Show();
}
用法
OpenExclusive<MyForm>(this);
注意:写在SO上并且完全未经测试
编写一个函数,通过其类名查找打开的表单,如果找到则打开它,并在最小化时恢复它。 当函数返回false时,表单将不会打开,您可以第一次打开。 这适用于我的winforms应用程序
public bool CheckIfFormIsAlreadyOpen(string className)
{
bool Result = false;
className = className.ToUpper();
int i = 0;
while ((i < Application.OpenForms.Count) && (Application.OpenForms[i].Name.ToUpper() != className))
{
i++;
}
if (i < Application.OpenForms.Count)
{
Application.OpenForms[i].Show();
Application.OpenForms[i].BringToFront();
if (Application.OpenForms[i].WindowState == FormWindowState.Minimized)
{
ShowWindowAsync(Application.OpenForms[i].Handle, 9); // 9 = SW_RESTORE
}
Result = true;
}
return Result;
}
用法:
if (!CheckIfFormIsAlreadyOpen("frmCustomers"))
{
frmCustomers form = new frmCustomers();
form.MdiParent = this.MdiParent;
form.Show();
}