C#如何在关闭表单之前将消息从一个表单发送到另一个表单?

时间:2013-06-20 01:27:08

标签: c# .net forms

我有一个程序,我希望它在关闭前询问确认。它只是一个带有问题的简单表单以及yesno按钮。如何将点击了哪个按钮的信息发送回主表单?我找到的所有解决方案都是为了打开这两种形式的通信,但是当在第二种方式中选择一个按钮时,它将关闭。任何提示或想法?

3 个答案:

答案 0 :(得分:1)

您描述的第二种表单类似于MessageBox ...您可以将其直接实现用作对话框。未经测试的例子:

DialogResult dr = MessageBox.Show("Are you Sure?",
    "Confirm Exit?",
    MessageBoxButtons.YesNo);
if (dr==DialogResult.Yes)
{
    // Do work If Yes
}else //if( dr == DialogResult.No)
{
    // Do work if No
}

See MSDN for MessageBox

答案 1 :(得分:0)

我倾向于这样做。

儿童表格代码:

        private bool _bDoSomething=false;

        public bool showForm()
        {
            this.ShowDialog();
            return _bDoSomething;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            _bDoSomething=true;
            this.Hide();
        }

然后是父表单的这种代码:

        dlgMyForm dlgMyForm = new dlgMyForm();
        if (dlgMyForm.showForm())
        {
          //do something
        }

答案 2 :(得分:0)

在主窗体中声明一个布尔值为public

 public Boolean check =false;

在第二种形式的FormClosing事件中执行以下操作

 private void Form2_FormClosing(Object sender, FormClosingEventArgs e) 
{
   DialogResult answer = MessageBox.Show("[Your text]",MessageBoxButtons.YesNo)

   if(answer == DialogResult.Yes)
     {

       Form1.check=True; //if button yes is clicked 
                         // set the form1 check variable to True and closes form2

     }
   else
     {
          Form1.check=False; //if button no is clicked 
                           // set the form1 check variable to False and cancel form 
                           // closing                                  
          e.Cancel=True;
     }


}

使用布尔变量检查在form1

中进行进一步处理