Winforms应用程序托管在WPF应用程序

本文关键字:应用程序 WPF Winforms | 更新日期: 2023-09-27 18:04:28

我需要在WPF应用程序上托管一个WinForms应用程序。我遵循了这里的步骤,但我有一个错误:

System.Reflection。TargetInvocationException未处理消息:Se producjo una excepción en el destino de la invocación.

怎么了?我正在使用VS2012和。net 4.5。WinForms应用程序只是一个FormButton

Winforms应用程序托管在WPF应用程序

事件点击显示MessageBox,显示Hello World消息。

我以前使用过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");
    }
}