简体   繁体   中英

Cancel form closing from some event

I want my formClosing event to cancel its closing operation if the SaveFileDialog , in my SaveAs Click event, is Cancel

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

void form1_FormClosing (object sender, FormClosingEventArgs e) 
{
    if (isContentChanged) 
    {
        DialogResult result = MessageBox.Show ("Do you want to save [ "+this.Text+"] ?", "Save", MessageBoxButtons.YesNoCancel);
        if (result == DialogResult.Yes) 
        {
            saveAsToolStripMenuItem_Click (sender, e);
        } 
        else if (result == DialogResult.Cancel) 
            e.Cancel = true;
    }
}


private void saveAsToolStripMenuItem_Click (object sender, EventArgs e) 
{
    SaveFileDialog sfd = new SaveFileDialog ();
    sfd.Filter = "Drawing Files | *.drg";
    DialogResult result = sfd.ShowDialog ();
    if (result == DialogResult.OK) {
        SaveFile (sfd.FileName);
        isContentChanged = false;
    } 
    else if (result == DialogResult.Cancel) 
    {
        // NEED TO CANCEL FORM CLOSING HERE   
    }
}

Is it possible? If yes, how?

Try this:

private void saveAsToolStripMenuItem_Click (object sender, EventArgs e) 
{
   ...

   if (result == DialogResult.OK) 
   {
       ...         
   } 
   else if (result == DialogResult.Cancel) 
   {  
       ((FormClosingEventArgs) e).Cancel = true; 
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM