Answered prevent close window

  • Wednesday, April 11, 2012 9:11 PM
     
      Has Code

    Hi All.

    To prevent to close child form I create code

        Private Sub FormDetail_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles Me.Closing
            Dim result As MessageBoxResult = MessageBox.Show("Close this window?", "Window Closing", MessageBoxButton.YesNo, MessageBoxImage.Warning)
    
            If result = MessageBoxResult.No Then
                ' If user doesn't want to close, cancel closure
                e.Cancel = True
            End If
        End Sub
    

    But when I click the close button on Main form the message for prevent to close also is popup. How to illuminate message when close Main form? Or how modify code in case if I close child form will popup message which I created and in case when I close main form will popup dialog box with message: "Close this project?"

    Thanks.

All Replies

  • Thursday, April 12, 2012 7:13 AM
    Moderator
     
     Answered Has Code

    Hi eugzl,

    You could register your event to different window, for example,

     mainWindow.Closing += new CancelEventHandler(MainWindow_Closing);
    void MainWindow_Closing(object sender, CancelEventArgs e)
    {
        MessageBoxResult result = MessageBox.Show("MainWindow close", "Window Closing", MessageBoxButton.YesNo, MessageBoxImage.Warning);
    
        if (result == MessageBoxResult.No)
        {
            // If user doesn't want to close, cancel closure
            e.Cancel = true;
        }
        //throw new NotImplementedException();
    }

    As for your Child window, you could register event before show it:

     Window ChildWindow = new Window();
                ChildWindow.Owner = this;
                ChildWindow.Closing += new CancelEventHandler(ChildWindow_Closing);
                ChildWindow.Show();
    void ChildWindow_Closing(object sender, CancelEventArgs e)
    {
        MessageBoxResult result = MessageBox.Show("Close this window?", "Window Closing", MessageBoxButton.YesNo, MessageBoxImage.Warning);
    
        if (result == MessageBoxResult.No)
        {
            // If user doesn't want to close, cancel closure
            e.Cancel = true;
        }
    }

    Best regards,


    Sheldon _Xiao[MSFT]
    MSDN Community Support | Feedback to us
    Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

  • Tuesday, May 01, 2012 8:27 AM
    Moderator
     
     

    Hi eugzl,
     
    I am marking your issue as "Answered", if you have new findings about your issue, please let me know.

    Best regards,


    Sheldon _Xiao[MSFT]
    MSDN Community Support | Feedback to us
    Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.