WindowsFormsHost Controls - Exception Handling

I have a WPF window that requires multiple WindowsFormHost controls. I noticed that if I model the control in this way, then the Exceptions do not surface and are silently handled, that is, they are only visible using the SharpDevelop Debugging option "Pause when handling exceptions".

How can I avoid this behavior?

I tested this by throwing an exception in the window-loaded event handler code. If I comment out one of the WindowsFormsHost controls, the exception handling is just as normal and the code breaks, but if left as shown in the code below, the window appears as if the exception was caught.

<?xml version="1.0" encoding="utf-8"?>
        x:Class="TEST.Window1" xmlns="" xmlns:x=""
                    Height="150" />
                    Height="150" />
            <WindowsFormsHost Grid.Row="0" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" />
            <WindowsFormsHost Grid.Row="1" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" />

/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
    public Window1()
        this.Loaded += new RoutedEventHandler(Window1_Loaded);

    void Window1_Loaded(object sender, RoutedEventArgs e)
        throw new ApplicationException("TEST");



source to share

1 answer

This is due to the intermediate window intermediate stack that WindowsFormsHost creates to pass Windows messages to Windows Forms.

It is based on the almost standard NativeWindow class , and unfortunately this class just uses an exception by default. You can have a look at it with Reflector or any other IL inspection tool. The heart of this class is this method:

private IntPtr Callback(IntPtr hWnd, int msg, IntPtr wparam, IntPtr lparam)
        // process message
    catch (Exception exception)


By default, the OnThreadException ... method is empty. In theory, you could create a class that derives from WindowsFormsHost, especially the BuildWindowCore method . I tried to do this but it doesn't work as the WindowsFormsHost implementation uses a lot of private stuf ...



All Articles