如果表格已经打开,有没有办法阻止在MDI容器中打开某个表单?
答案 0 :(得分:34)
您可以遍历OpenForms集合以检查是否已存在给定类型的表单:
foreach (Form form in Application.OpenForms)
{
if (form.GetType() == typeof(MyFormType))
{
form.Activate();
return;
}
}
Form newForm = new MyFormType();
newForm.MdiParent = this;
newForm.Show();
答案 1 :(得分:3)
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。
答案 2 :(得分:1)
答案 3 :(得分:1)
此代码正常工作
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();
}
答案 4 :(得分:0)
虽然这篇文章很老,但我认为这会增加一些帮助。
如果表格也最小化,需要处理。这是完整的例子:
method(T anyClass)
答案 5 :(得分:0)
此代码适用于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()
Return
End If
Next
form_name .MdiParent = Me
form_name .Show()
答案 6 :(得分:0)
可以使用Generics(在C#和VB.net下面选项)实现一个方法,如果需要打开不同的MDI表单,这可能很有用。
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);
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)
答案 7 :(得分:0)
此代码在C#中对我有用
<div class="book">
<div class="book__form"></div>
</div>