2012-06-27 19 views
0

如何爲表單X(頂部最右側)和關閉按鈕創建相同的功能。這2個需要表現得都 這是我在btnClose_ClickC#表單X關閉和btnclose功能相同

 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 ..

感謝ü

回答

6

只要把this.Close()在btnClose_Click( )事件。然後將所有剩餘的邏輯(需要編輯一些)移動到frmData_FormClosing()事件中,如果要取消關閉表單,請調用e.Cancel = true;(在您的情況下,如果存在未保存的更改並且用戶單擊「是」 。在提示

下面是一個例子(我只是剪切和粘貼在記事本,讓公平的警告):

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(); 
    } 
}