C# - FormClosing event handling

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Daniel Walker
    New Member
    • Mar 2008
    • 2

    C# - FormClosing event handling

    Hey there,

    I'm having a problem with this code snippet: (C#)

    Code:
    private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
            {
                e.Cancel = true;
                OtherForm dialog = new OtherForm();
                DialogResult result = dialog.ShowDialog();
                if (result == DialogResult.OK)
                {
                    Application.Exit();
                }
            }
    MainForm throws the event, doesn't close, and shows the dialog.
    If I add a watch on result, I can see it gets "OK" as its value, however, the application does not close. Any thoughts?
  • misza
    New Member
    • Feb 2008
    • 13

    #2
    Hi,

    The proper way to control whether to close a form in FormClosing event is to set the "e.Cancel" property:
    - to false when you want to allow it to close
    - to true to prevent closing

    so as I understand, you want to do something like this:
    Code:
    private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
    {
    OtherForm other = new OtherForm();
    DialogResult resutl = other.ShowDialog();
    if(result != DialogResult.OK)
    {
       e.Cancel = true;
    }
    
    }
    In other words you don't have to allow the form to close in FormClosing, just prevent it if needed.

    Hope this solves your problem,
    Michal

    Comment

    • Daniel Walker
      New Member
      • Mar 2008
      • 2

      #3
      Thanks a lot for the reply. I actually found this out right after I posted it.

      Comment

      • Plater
        Recognized Expert Expert
        • Apr 2007
        • 7872

        #4
        All Application.Exi t() does it send a windows message to close the form....which it already does to get to that event.

        Comment

        Working...