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"?>
    <Window
        x:Class="TEST.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="TEST"
        Height="300"
        Width="300">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition
                    Height="150" />
                <RowDefinition
                    Height="150" />
            </Grid.RowDefinitions>
            <WindowsFormsHost Grid.Row="0" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" />
            <WindowsFormsHost Grid.Row="1" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" />
        </Grid>
    </Window>

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

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

      

+3


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)
{
    try
    {
        // process message
    }
    catch (Exception exception)
    {
        this.OnThreadException(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 ...

+1


source







All Articles