我有2个表格,第一个 - 主要,第二个孩子,从thred打开。如果儿童表格已经打开,我需要打开儿童表格,关闭它并只显示一个儿童表格。
主要形式:
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void showChildForms(object sender, EventArgs e)
{
createThread();
createThread();
createThread();
}
private void createThread()
{
var t = new Thread(
() =>
{
this.Invoke(new Action(delegate
{
showForm();
}));
}
);
t.IsBackground = true;
t.Start();
}
private void showForm()
{
var form2 = new ChildForm();
form2.ShowDialog();
}
}
儿童形式:
public partial class ChildForm : Form
{
public ChildForm()
{
InitializeComponent();
}
}
答案 0 :(得分:0)
首先,你的问题对我来说并不是很清楚。但.. 一种简单的方法是在它们之间共享一个bool。 另一个提示:当你完成它时,总是处理你的形式。 这里的主题是浪费资源......你应该过度思考你的方法。
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
public bool ChildIsOpen {get; set;}
private void showChildForms(object sender, EventArgs e)
{
createThread();
createThread();
createThread();
}
private void createThread()
{
if(ChildIsOpen)
return;
var t = new Thread(
() =>
{
this.Invoke(new Action(delegate
{
showForm();
}));
}
);
t.IsBackground = true;
t.Start();
}
private void showForm()
{
using (ChildForm childForm = new ChildForm())
{
childForm .Load += (o, args) => ChildIsOpen = true;
childForm .Closed += (o, args) => ChildIsOpen = false;
childForm .ShowDialog();
}
}
}
儿童形式(未改变):
public partial class ChildForm : Form
{
public ChildForm()
{
InitializeComponent();
}
}
答案 1 :(得分:0)
如果我的理解是对的。
如果不符合您的需求,请更清楚地评论您的要求
以您的主要表格
public partial class MainForm : Form
{
var form2 = new ChildForm();
public MainForm()
{
InitializeComponent();
}
private void showChildForms(object sender, EventArgs e)
{
createThread();
createThread();
createThread();
}
private void createThread()
{
var t = new Thread(
() =>
{
this.Invoke(new Action(delegate
{
showForm();
}));
}
);
t.IsBackground = true;
t.Start();
}
private void showForm()
{
Form res = new Form();
foreach (Form form in Application.OpenForms)
{
if (form.Text == "Form2")//or form.Name u can use how you are assigning in form2
{
res = form;
break;
}
}
res.Close();
// Do what ever.The above part will close the previous instances of the Forms.
}
}