表格结束帮助

时间:2010-06-01 14:46:25

标签: c#

如何在表单关闭事件中调用button1_Click事件,这样我就不必复制并粘贴button1_Click中的代码?

      public void button1_Click(object sender, EventArgs e)
   {
       //Yes or no message box to exit the application
       DialogResult Response;
       Response = MessageBox.Show("Are you sure you want to Exit?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
       if (Response == DialogResult.Yes)

           // Exits the application
           Application.Exit();
   }

   public void xGameThemeComboBox_SelectedIndexChanged(object sender, EventArgs e)
   {
       string folder = Application.StartupPath;
       string theme = (string)xGameThemeComboBox.Items[xGameThemeComboBox.SelectedIndex];
       string path = System.IO.Path.Combine(folder, theme + ".jpg");
       Image newImage = new Bitmap(path);
       if (this.BackgroundImage != null) this.BackgroundImage.Dispose();
       {
           this.BackgroundImage = newImage;
       }

   }

   private void xGameForm_FormClosing(object sender, FormClosingEventArgs e)
   {
      // call button1_Click here 
   }

6 个答案:

答案 0 :(得分:4)

你真正需要做的事情:

      private bool ShowClose()
   {
       //Yes or no message box to exit the application
       DialogResult Response;
       Response = MessageBox.Show("Are you sure you want to Exit?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
       return Response == DialogResult.Yes;
   }

      public void button1_Click(object sender, EventArgs e)
   {
       Close();
   }

private void xGameForm_FormClosing(object sender, FormClosingEventArgs e)
   {
      e.Cancel = !ShowClose();
   }

答案 1 :(得分:1)

最好将button1_Click事件中的代码提取到方法中,然后从两个事件中调用该方法。

答案 2 :(得分:1)

将按钮方法的内容解压缩到它自己的方法中,然后从两个点调用该方法。

答案 3 :(得分:0)

button1_Click(null, null);

答案 4 :(得分:0)

您不应该在按钮中显示MessageBox。

您只需在按钮中拨打Application.Exit()即可,FormClosing事件可以显示确认消息。

答案 5 :(得分:0)

Application.Exit在所有打开的表单上引发FormClosing事件:

  

引发FormClosing事件   形式所代表的每一种形式   OpenForms财产。这个事件可以   通过设置取消取消   他们FormClosingEventArgs的财产   参数为true。

     

如果其中一个处理程序取消   事件,然后Exit没有返回   进一步的行动。否则,一个   每个人都会提出FormClosed个事件   打开表单,然后是所有运行的消息   循环和表格已关闭。

我会像这样重写它:

public void button1_Click(object sender, EventArgs e)
{
    // Exits the application
    Application.Exit();
}

private void xGameForm_FormClosing(object sender, FormClosingEventArgs e)
{
    //Yes or no message box to exit the application
    DialogResult Response;
    Response = MessageBox.Show("Are you sure you want to Exit?", "Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
    if (Response == DialogResult.No)
    {
        // Cancel the close, prevents applications from exiting.
        e.Cancel = true;
    } else {
        Application.Exit();
    }

}