在WPF应用程序上托管的Winforms App

时间:2013-03-18 19:14:05

标签: c# wpf winforms

我需要在WPF应用上托管一个WinForms应用。我按照here步骤进行了操作,但我发现了一个错误:

  

System.Reflection.TargetInvocationException未处理   消息:Se produjounaexsentpciónenel destino delainvocación。

怎么了?我正在使用VS2012和.NET 4.5。 WinForms应用只有FormButton。点击事件会显示MessageBox,并显示消息Hello World

1 个答案:

答案 0 :(得分:1)

之前我使用过WindowsFormsIntegration.dll,它运行正常。这应该可以帮助你开始。首先添加对WindowsFormsIntegration的引用。然后...

using System.Windows.Forms.Integration;

...

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        var form = new Form1();
        form.TopLevel = false;

        WindowsFormsHost host = new WindowsFormsHost();
        host.Child = form;
        host.VerticalAlignment = System.Windows.VerticalAlignment.Top;
        host.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;


        grid.Children.Add(host);
    }

...

<Window x:Class="WpfSandbox.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        Loaded="Window_Loaded">
    <Grid x:Name="grid">
    </Grid>
</Window>

现在是简单的winform

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show("hello");
    }
}