【问题标题】:Hook in befor App.Exit在 App.Exit 之前挂钩
【发布时间】:2018-03-22 09:13:33
【问题描述】:

这是我的问题:

在我的 WPF 应用程序中,我有一个 MyBaseControl(派生自 System.Windows.Controls.ContentControls)和许多派生自 MyBaseControlMyCustomControls。在关闭应用程序之前,我需要对我的所有MyCustomControls 进行一些存储和清理操作。 这是一些代码:

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

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

App_OnExit() 中,我做了最后需要完成的操作。 我试图在MyBaseControl 的析构函数中进行清理操作,但这在App_OnExit() 之后调用。 AppDomain.CurrentDomain.ProcessExit 也有同样的问题。

当我通过 ALT+F4 退出应用程序时,ContentControl.ClosedContentControl.Unloaded 事件不会发生。

我可以在哪里进行清理操作?

【问题讨论】:

    标签: c# wpf controls resource-cleanup application-shutdown


    【解决方案1】:

    我可以在哪里进行清理操作?

    在控件的父窗口的Closing 事件处理程序中:

    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...
        }
    }
    

    【讨论】:

    • 完美!谢谢;)
    【解决方案2】:

    你可以把它放到你的应用类中:

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

    修改退出事件处理程序:

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

    并修改您的基本控件:

    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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-03
      • 1970-01-01
      • 1970-01-01
      • 2018-04-27
      • 2011-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多