0

如何为表单 X(在右上角)和关闭按钮提供相同的功能。这两个需要表现得相似这就是我在 btnClose_Click 中所拥有的

     private void btnClose_Click(object sender, EventArgs e)
            {
                DialogResult result;
                int fileId = StaticClass.FileGlobal;
                if (DataDirty)
                {
                    string messageBoxText = "You have unsaved data. Do you want to save the changes and exit the form?";
                    MessageBoxButtons button = MessageBoxButtons.YesNo;
                    string caption = "Data Changed";
                    MessageBoxIcon icon = MessageBoxIcon.Question;
                    result = MessageBox.Show(messageBoxText, caption, button, icon);
                    if (result == DialogResult.No)
                    {
                        Program.fInput = new frmInputFiles(gtId, gName);
                        Program.fInput.Show();
                        this.Close();
                    }
                    if (result == DialogResult.Yes)
                    {
                        return;

                    }
                }
                else
                {
                    Program.fInput = new frmInputFiles(gPlantId, gPlantName);
                    Program.fInput.Show();
                    this.Close();

                }

            }

    Even on clicking the X to close the form,it should behave the same way as btnClose_Click

      private void frmData_FormClosing(object sender, FormClosingEventArgs e)
            {

        btnClose_Click(sender,e);//this doesnt seem to be working.
}

它正在无限循环中。我知道它正在这样做.. btnClose_Click() 有 this.Close() 调用 frmData_FormClosing.. 这反过来又调用 btnclose..

感谢你

4

1 回答 1

6

只需将 this.Close() 放在 btnClose_Click() 事件中。然后将所有其余逻辑(您需要对其进行一些编辑)移动到 frmData_FormClosing() 事件中,e.Cancel = true;如果您想取消关闭表单(在您的情况下,如果有未保存的更改并且用户单击 Yes on提示。

这是一个例子(我只是在记事本中剪切并粘贴,所以公平警告):

private void btnClose_Click(object sender, EventArgs e)
{
    this.Close();
}

private void frmData_FormClosing(object sender, FormClosingEventArgs e)
{
    if (DataDirty)
    {
        if (MessageBox.Show("You have unsaved data. Do you want to save the changes and exit the form?",
                            "Data Changed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
        {
            Program.fInput = new frmInputFiles(gtId, gName);
            Program.fInput.Show();
        }
        else
            e.Cancel = true;
    }
    else
    {
        Program.fInput = new frmInputFiles(gPlantId, gPlantName);
        Program.fInput.Show();
    }
}
于 2012-06-27T02:59:25.470 回答