我是C#的新手,我使用的是Windows窗体。
我有form1
和form2
,我在form2
中显示和隐藏form1
,如下所示:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Form2 frm2 = new Form2();
private void button_showForm2_Click(object sender, EventArgs e)
{
frm2.Show();
//I want to show the following message once form2 hides:
MessageBox.Show("Form2 is hidden. Continue processing next line of code");
}
}
在form2中:
private void button_HideForm2_Click(object sender, EventArgs e)
{
Hide();
}
当我运行上述代码并显示form2
时,form2
会同时显示messageBox
。我知道这是因为当使用Show()
方法时,它不保存程序流并继续执行下一行代码,而使用ShowDialog()
保存程序流,直到您关闭子表单。
我想要做的是(我不想使用ShowDialog()
):我想显示form2
,当你完成使用它并隐藏它时,我想显示上面的消息(在form1
隐藏form2
时。{/ p>
任何人都知道我该怎么做?谢谢你。
答案 0 :(得分:1)
我会以这种方式实现它
Form1中:
private void button_showForm2_Click(object sender, EventArgs e)
{
this.frm2 = new Form2(this);
this.frm2.Show();
}
public void ShowMessage()
{
MessageBox.Show("Form2 is hidden. Continue processing next line of code");
}
窗体2:
public Form1 _Form1 { get; private set; }
public Form2(Form1 _Form1) { this._Form1 = _Form1; }
private void button_HideForm2_Click(object sender, EventArgs e)
{
Hide();
this._Form1.ShowMessage();
}
答案 1 :(得分:0)
挂钩Form的VisibleChanged事件,当您的表单可见性发生变化时,您的代码将被触发。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Form2 frm2 = new Form2();
private void button_showForm2_Click(object sender, EventArgs e)
{
frm2.VisibleChanged += new EventHandler(this.FormVisibilityChanged);
frm2.Show();
}
private void FormVisibilityChanged(object sender, EventArgs e)
{
frm2.VisibleChanged -= new EventHandler(this.FormVisibilityChanged);
MessageBox.Show("Form2 is hidden. Continue processing next line of code");
}
}