Tom
Tom

Reputation: 91

WPF window on closing

I want send some data on server, before window close. I use event closing, but it doesn t wokr. Where is a problem?

    private void Window_Closing(object sender, RoutedEventArgs e)
    {
            _obj.CloseConnection();

    }

Upvotes: 3

Views: 6577

Answers (3)

Spydee
Spydee

Reputation: 79

You can also do it this way without overriding the OnClosing.

The constructor of the main window is

       public MainWindow()
    {
        InitializeComponent();
        Loaded += MainWindow_Loaded;
        Closing += MainWindow_Closing;
    }

Then create an event handler

        private void MainWindow_Closing(object? sender, System.ComponentModel.CancelEventArgs e)
    {
       // do something
     }

Note: This may not meet MVVM.

D

Upvotes: 0

Jobi Joy
Jobi Joy

Reputation: 50048

Try overriding OnClosing in the window code behind. There you have a chance to stop the window from closing if you have something else to do by setting e.Cancel = true.

    protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
    {
       bool isClosed = _obj.CloseConnection();

       if(!isClosed)
          e.Cancel = true;

    }

Upvotes: 7

Maurizio Reginelli
Maurizio Reginelli

Reputation: 3222

Did you check if there's a problem on _obj.CloseConnection()? Try to debug your code and check if the event handler is called.

Upvotes: 0

Related Questions