我有一个带有UserControl
(ucModule2)的主窗体(Form1)。 ucModule2包含一个按钮(simpleButton1),用于打开另一个表单(Form2)。在Form1上,我有一个按钮(UsrCtrlDialog)应关闭Form2。我有两种情况:
场景1:我的ucModule2.cs:
public partial class ucModule2 : UserControl
{
public static Form2 fr2 = new Form2();
private void simpleButton1_Click(object sender, EventArgs e)
{
//Form2 fr2 = new Form2();
fr2.Show();
fr2.TopMost = true;
textModule2 = textBox_ucModule2.Text;
}
}
用于关闭Form2的Form1的按钮:
private void UsrCtrlDialog_Click(object sender, EventArgs e)
{
// Form2 fr2 = new Form2();
ucModule2.fr2.TopMost = false;
ucModule2.fr2.Close();
ucModule2.fr2.Dispose();
}
在这种情况下,Form2仅打开一次,并且当关闭Form1中的UsrCtrlDialog按钮时将其关闭。但是,如果我想再次打开Form2,则会收到System.ObjectDisposedException
异常(“无法访问已处置的对象。”在fr2.Show();
上,我知道当我再次打开Form2时,不会创建Form2类型的新对象。在关闭旧的Form2之后,我该怎么办才能打开它?
方案2:我的ucModule2.cs:
public partial class ucModule2 : UserControl
{
//public static Form2 fr2 = new Form2();
private void simpleButton1_Click(object sender, EventArgs e)
{
Form2 fr2 = new Form2();
fr2.Show();
fr2.TopMost = true;
textModule2 = textBox_ucModule2.Text;
}
}
在这种情况下,单击simpleButton1
可以打开许多Form2窗口。例如,我按3次simpleButton1
。我将有3个Form2窗口。当我按Form1的UsrCtrlDialog按钮时,如何关闭3个Form2窗口?如何将fr2对象从ucModule2.cs转换为Form1.cs?
@ Jimi,我的ucModule2.cs看起来像这样:
public partial class ucModule2 : UserControl
{
public Form FormInstance { get; private set; }
private static ucModule2 _instance;
public static string textModule2;
public static ucModule2 Instance
{
get
{
if (_instance == null)
_instance = new ucModule2();
return _instance;
}
}
public void SetForm(Type formType)
{
if (this.FormInstance == null)
{
this.FormInstance = (Form)Activator.CreateInstance(formType);
}
}
public ucModule2()
{
InitializeComponent();
SetForm(typeof(Form2));
}
private void simpleButton1_Click(object sender, EventArgs e)
{
this.FormInstance.Show();
}
}
我想念什么?