【问题标题】:Winforms App hosted on WPF App托管在 WPF 应用程序上的 Winforms 应用程序
【发布时间】:2013-07-10 20:59:16
【问题描述】:

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

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

怎么了?我正在使用 VS2012 和 .NET 4.5。 WinForms 应用程序只是一个Form 和一个Button。事件点击显示 MessageBox 和消息 Hello World 仅此而已。

【问题讨论】:

  • 发布您的代码和 XAML。
  • 另外,你要那个干什么?它看起来像一个可怕的黑客。

标签: c# wpf winforms


【解决方案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");
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多