如果该表单已经打开,是否有办法防止在 MDI 容器中打开该表单?
7 回答
您可以对 OpenForms 集合进行交互以检查是否已经存在给定类型的表单:
foreach (Form form in Application.OpenForms)
{
if (form.GetType() == typeof(MyFormType))
{
form.Activate();
return;
}
}
Form newForm = new MyFormType();
newForm.MdiParent = this;
newForm.Show();
AFAIK没有标准的方法。你必须自己实现它。我会这样做:
class TheForm: Form
{
private static TheForm Instance;
private TheForm() // Constructor is private
{
}
public static Show(Form mdiParent)
{
if ( Instance == null )
{
// Create new form, assign it to Instance
}
else
Instance.Activate(); // Not sure about this line, find the appropriate equivalent yourself.
}
protected override OnFormClose(EventArgs e)
{
Instance = null;
base.OnFormClose(e);
}
}
如果关注线程安全,请添加适当lock
的 s.
此代码有效
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
foreach (Form form in Application.OpenForms)
{
if (form.GetType() == typeof(Form2))
{
form.Activate();
return;
}
}
Form2 newForm = new Form2();
newForm.MdiParent = this;
newForm.Show();
}
虽然这篇文章很老,但我认为这会增加帮助。
如果表单也被最小化,则需要处理。这是完整的示例:
foreach (Form form in this.MdiChildren)
{
if (form.GetType() == typeof(frmMain))
{
if (form.WindowState == FormWindowState.Minimized)
{
form.WindowState = FormWindowState.Normal;
}
form.Activate();
return;
}
}
Form frm = new frmMain();
frm.MdiParent = this;
frm.Show();
此代码在 vb.net 中为我工作
For Each f As Form In Application.OpenForms
If TypeOf f Is form_name Then
f.Activate()
f.WindowState = FormWindowState.Normal
f.StartPosition = FormStartPosition.WindowsDefaultLocation
f.WindowState = FormWindowState.Maximized
Return
End If
Next
form_name .MdiParent = Me
form_name .Show()
可以使用泛型(在 C# 和 VB.net 选项下方)实现方法,如果需要打开不同的 MDI 表单,这可能很有用。
C#
private void OpenMDI<T>(bool multipleInstances)
where T : Form, new()
{
if (multipleInstances == false)
{
// Look if the form is open
foreach (Form f in this.MdiChildren)
{
if (f.GetType() == typeof(T))
{
// Found an open instance. If minimized, maximize and activate
if (f.WindowState == FormWindowState.Minimized)
{
f.WindowState = FormWindowState.Maximized;
}
f.Activate();
return;
}
}
}
T newForm = new T();
newForm.MdiParent = this;
newForm.Show();
}
按如下方式使用它(指示false
以multipleInstances
防止它们)
OpenMDI<Form2>(false);
VB.NET
Public Sub Open_MDI(Of T As {New, Form})(bMultipleInstances As Boolean)
If bMultipleInstances = False Then
For Each f As Form In Me.MdiChildren
If TypeOf f Is T Then
If (f.WindowState = FormWindowState.Minimized) Then
f.WindowState = FormWindowState.Maximized;
End If
f.Activate()
Exit Sub
End If
Next
End If
Dim myChild As New T()
myChild.MdiParent = Me
myChild.Show()
End Sub
按如下方式使用它(指示False
以bMultipleInstances
防止它们)
Open_MDI(Of Form2)(False)
这段代码在 C# 中对我有用
private void btn1_Click(object sender, EventArgs e)
{
Form2 new_form = new Form2();
if (new_form.visible)
new_form.Show();
else
new_form.ShowDialog();
}