Window.Closing Evento

Definición

Se produce inmediatamente después de llamar a Close() y se puede controlar para que se cancele el cierre de la ventana.Occurs directly after Close() is called, and can be handled to cancel window closure.

public:
 event System::ComponentModel::CancelEventHandler ^ Closing;
public event System.ComponentModel.CancelEventHandler Closing;
member this.Closing : System.ComponentModel.CancelEventHandler 
Public Custom Event Closing As CancelEventHandler 

Excepciones

Se establece la propiedad Visibility o se llama a Show(), ShowDialog() o Close() mientras se cierra una ventana.Visibility is set, or Show(), ShowDialog(), or Close() is called while a window is closing.

Ejemplos

En el ejemplo siguiente se Window muestra un que determina si necesita la intervención del usuario para cerrarse.The following example demonstrates a Window that determines whether it needs user intervention to close.

<Window 
  x:Class="CSharp.DataWindow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Closing="DataWindow_Closing"  
    >
  <Grid>
    <TextBox Name="documentTextBox" AcceptsReturn="True" AcceptsTab="True" TextChanged="documentTextBox_TextChanged"></TextBox>
  </Grid>
</Window>
using System; // EventArgs
using System.ComponentModel; // CancelEventArgs
using System.Windows; // window

namespace CSharp
{
    public partial class DataWindow : Window
    {
        // Is data dirty
        bool isDataDirty = false;

        public DataWindow()
        {
            InitializeComponent();
        }

        void documentTextBox_TextChanged(object sender, EventArgs e)
        {
            this.isDataDirty = true;
        }

        void DataWindow_Closing(object sender, CancelEventArgs e)
        {
            MessageBox.Show("Closing called");

            // If data is dirty, notify user and ask for a response
            if (this.isDataDirty)
            {
                string msg = "Data is dirty. Close without saving?";
                MessageBoxResult result = 
                  MessageBox.Show(
                    msg, 
                    "Data App", 
                    MessageBoxButton.YesNo, 
                    MessageBoxImage.Warning);
                if (result == MessageBoxResult.No)
                {
                    // If user doesn't want to close, cancel closure
                    e.Cancel = true;
                }
            }
        }
    }
}
Imports System ' EventArgs
Imports System.ComponentModel ' CancelEventArgs
Imports System.Windows ' window

Namespace VisualBasic
    Partial Public Class DataWindow
        Inherits Window
        ' Is data dirty
        Private isDataDirty As Boolean = False

        Public Sub New()
            InitializeComponent()
        End Sub

        Private Sub documentTextBox_TextChanged(ByVal sender As Object, ByVal e As EventArgs)
            Me.isDataDirty = True
        End Sub

        Private Sub DataWindow_Closing(ByVal sender As Object, ByVal e As CancelEventArgs)
            MessageBox.Show("Closing called")

            ' If data is dirty, notify user and ask for a response
            If Me.isDataDirty Then
                Dim msg As String = "Data is dirty. Close without saving?"
                Dim result As MessageBoxResult = MessageBox.Show(msg, "Data App", MessageBoxButton.YesNo, MessageBoxImage.Warning)
                If result = MessageBoxResult.No Then
                    ' If user doesn't want to close, cancel closure
                    e.Cancel = True
                End If
            End If
        End Sub
    End Class
End Namespace

Comentarios

Closingse puede controlar para detectar cuándo se cierra una ventana (por ejemplo, cuando Close se llama a).Closing can be handled to detect when a window is being closed (for example, when Close is called). Además, Closing se puede usar para evitar que una ventana se cierre.Furthermore, Closing can be used to prevent a window from closing. Para evitar que se cierre una ventana, puede establecer la Cancel propiedad CancelEventArgs del argumento en true.To prevent a window from closing, you can set the Cancel property of the CancelEventArgs argument to true.

El Closing evento se desencadena cuando Close se llama a, si se hace clic en el botón cerrar de una ventana o si el usuario presiona ALT + F4.The Closing event is raised when Close is called, if a window's Close button is clicked, or if the user presses ALT+F4.

Si la ventana propietaria abrió una ventana propiedad mediante Showy la ventana propietaria está cerrada, no se genera el evento de la ventana de Closing propiedad.If an owned window was opened by its owner window using Show, and the owner window is closed, the owned window's Closing event is not raised. Si el propietario de una ventana está cerrado (vea Owner), Closing no se genera en la ventana de propiedad.If the owner of a window is closed (see Owner), Closing is not raised on the owned window.

Si Shutdown se llama a, Closing se genera el evento para cada ventana.If Shutdown is called, the Closing event for each window is raised. Sin embargo, Closing si se cancela, se omite la cancelación.However, if Closing is canceled, cancellation is ignored.

Si una sesión finaliza debido a que un usuario cierra la sesión o Closing se apaga, no se SessionEnding genera; identificador para implementar código que cancela el cierre de la aplicación.If a session ends because a user logs off or shuts down, Closing is not raised; handle SessionEnding to implement code that cancels application closure.

Si desea mostrar y ocultar una ventana varias veces durante la vigencia de una aplicación y no desea volver a crear una instancia de la ventana cada vez que la muestre, puede controlar el Closing evento, cancelarlo y llamar al Hide método.If you want to show and hide a window multiple times during the lifetime of an application, and you don't want to reinstantiate the window each time you show it, you can handle the Closing event, cancel it, and call the Hide method. A continuación, puede llamar Show a en la misma instancia para volver a abrirla.Then, you can call Show on the same instance to reopen it.

Se aplica a

Consulte también: