【问题标题】:WindowsFormsHost Controls - Exception HandlingWindowsFormsHost 控件 - 异常处理
【发布时间】:2012-04-01 07:17:21
【问题描述】:

我有一个需要多个 WindowsFormHost 控件的 WPF 窗口。我注意到,如果我像这样对控件进行建模,那么异常不会浮出水面并且会被静默处理,即仅使用 SharpDevelop 的调试选项“处理异常时暂停”才可见。

如何避免这种行为?

我已经通过在 Window 的 Loaded Event Handler 代码中抛出异常来测试这一点。如果我注释掉其中一个 WindowsFormsHost 控件,异常处理正常并且代码中断,但如果如下代码所示,则窗口显示为好像捕获到异常一样。

<?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");
    }
}

【问题讨论】:

标签: .net wpf exception windowsformshost


【解决方案1】:

这是由于 WindowsFormsHost 为处理 Windows 消息的 Windows 窗体技术而创建的中间窗口互操作堆栈。

它基于一个几乎标准的NativeWindow 类,不幸的是,这个类默认只吃异常。您可以使用 Reflector 或任何其他 IL 检查工具查看它。这个类的核心是这个方法:

private IntPtr Callback(IntPtr hWnd, int msg, IntPtr wparam, IntPtr lparam)
{
    try
    {
        // process message
    }
    catch (Exception exception)
    {
        this.OnThreadException(exception);
    }
    ...
}

默认情况下,OnThreadException 方法是……空的。理论上,您可以创建一个派生自 WindowsFormsHost 的类,尤其是 BuildWindowCore 方法。我试过这样做,但它不起作用,因为 WindowsFormsHost 实现使用了很多私有 stuf....

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-25
    • 1970-01-01
    相关资源
    最近更新 更多