C# WPF应用程序,使用HwndHost托管exe,childapp自动关闭,获取无效的windows句柄异常

C# WPF应用程序,使用HwndHost托管exe,childapp自动关闭,获取无效的windows句柄异常,c#,wpf,C#,Wpf,如果您有一个WPF应用程序,我正在使用它来托管外部可执行文件。我使用System.Diagnostics.Process启动应用程序 如果hostApp控制关闭,并且可以在process.kill之前调用HwndHost.Dispose(),则它工作正常。DestroyWindowOverride按其应该的方式被调用,所有内容都将退出 如果childapp自行关闭,则我正在捕获进程。已退出事件。我马上打电话给警察。我不会得到即时异常或每次异常,但我经常会得到带有“无效windows句柄”错误的W

如果您有一个WPF应用程序,我正在使用它来托管外部可执行文件。我使用System.Diagnostics.Process启动应用程序

如果hostApp控制关闭,并且可以在process.kill之前调用HwndHost.Dispose(),则它工作正常。DestroyWindowOverride按其应该的方式被调用,所有内容都将退出

如果childapp自行关闭,则我正在捕获进程。已退出事件。我马上打电话给警察。我不会得到即时异常或每次异常,但我经常会得到带有“无效windows句柄”错误的Win32异常。我没有通过窗口覆盖接到电话

我已尝试清除DataContext,从可视树中删除该对象。试图捕获异常

我使用的是dwaneed.hwndhestex(HwndHost的一个派生版本)。我希望使用直接的HwndHost也会遇到同样的问题

有什么想法吗

 at MS.Win32.UnsafeNativeMethods.EnableWindow(HandleRef hWnd, Boolean enable)
位于System.Windows.Interop.HwndHost.OneEnabledChanged(对象发送方,DependencPropertyChangedEventArgs e) 在System.Windows.UIElement.RaiseDependencyPropertyChanged处(EventPrivateKey、DependencyPropertyChangedEventArgs) 在System.Windows.UIElement.OnIsEnabledChanged(DependencyObject d,DependencyPropertyChangedEventArgs e) 位于System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e) 位于System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e) 位于System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs参数) 在System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex EntryIndex,DependencyProperty dp,PropertyMetadata,EffectiveValueEntry oldEntry,EffectiveValueEntry&newEntry,布尔强制WithDeferredReference,布尔强制WithCurrentValue,OperationType OperationType) 位于System.Windows.DependencyObject.ImpresseValue(DependencyProperty dp) 位于System.Windows.UIElement.InvalidateForceInheritPropertyOnChildren(Visual v,DependencyProperty属性) 在System.Windows.UIElement.OnIsEnabledChanged(DependencyObject d,DependencyPropertyChangedEventArgs e) 位于System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
在System.Windows.Framew

上,HwndHost具有IsEnabledChanged事件的处理程序。在实现中,调用了unsafentiveMethods.EnableWindow(\u hwnd,value),它会在子应用程序关闭时抛出异常(不是每次都是,但太频繁了)

在这种情况下,我能够断开为响应IsEnabledChanged事件而调用的委托。看来我不需要它。如果我这样做了,我可以将处理程序的实现重定向到我自己的代码,并通过适当的IsAlive检查来修复它

 private void ClearIsEnabledEvent()
    {
        FieldInfo handlerInfo = typeof(HwndHost).GetField("_handlerEnabledChanged", BindingFlags.Instance | BindingFlags.NonPublic);

        // can't do this, HwndHost needs it to be NOT null
        //handlerInfo.SetValue(this,null);

        // replace functionality with my own code (adjust\fix for my own context)
        //handlerInfo.SetValue(this, new DependencyPropertyChangedEventHandler(OnEnabledChanged));

        // in this case, it doesn't appear anything implementation is needed
        // just an empty delegate
        if (handlerInfo != null)
            handlerInfo.SetValue(this, new DependencyPropertyChangedEventHandler(delegate { }));
    }