0

Here is my problem:

In my WPF application I have a MyBaseControl (derives from System.Windows.Controls.ContentControls) and a lot of MyCustomControls which derives from MyBaseControl. I need to do some storing and cleanup operations for all my MyCustomControls befor the application is closed. Here is some code:

public abstract class MyBaseControl : ContentControl
{
// Do some smart stuff.
}

App.Exit += new System.Windows.ExitEventHandler(App.App_OnExit);

In App_OnExit() I do the really last operations that need to be done. I tried to do my cleanup operations in the destructor of MyBaseControl but this is called after App_OnExit(). Same problem with AppDomain.CurrentDomain.ProcessExit.

The ContentControl.Closed and ContentControl.Unloaded events don't occour when I exit the application via ALT+F4.

Where can I hook in to do my cleanup operations?

Felix
  • 105
  • 1
  • 7

2 Answers2

2

Where can I hook in to do my cleanup operations?

In a Closing event handler for the parent window of the control:

public abstract class MyBaseControl : ContentControl
{
    public MyBaseControl()
    {
        Loaded += MyBaseControl_Loaded;
    }

    private void MyBaseControl_Loaded(object sender, RoutedEventArgs e)
    {
        Window parentWindow = Window.GetWindow(this);
        parentWindow.Closing += ParentWindow_Closing;
        Loaded -= MyBaseControl_Loaded;
    }

    private void ParentWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        //cleanup...
    }
}
mm8
  • 163,881
  • 10
  • 57
  • 88
0

You can put it to your application class:

public delegate void TimeToCleanUpEventHandler();
public event TimeToCleanUpEventHandler TimeToCleanUp;

modify Exit event handler:

App.Current.Exit += ((o, e) => { TimeToCleanUp?.Invoke(); App.App_OnExit(o, e); });

and modify your base control:

public abstract class MyBaseControl : ContentControl
{
    public MyBaseControl()
    {
        (App.Current as MyApp).TimeToCleanUp += CleanItUp;
    }

    public virtual void CleanItUp()
    {
        (App.Current as MyApp).TimeToCleanUp -= CleanItUp;
        //do stuff;
    }
}
Rekshino
  • 6,954
  • 2
  • 19
  • 44