在WindowsFormsHost中插入窗体时出现ArgumentException

时间:2014-01-04 19:53:16

标签: c# .net wpf forms com

在WPF应用中,我创建了WindowsFormsHost,并希望在其中插入包含Form / COM控件的Activex。但后来我得到了:

A first chance exception of type 'System.ArgumentException' occurred in WindowsFormsIntegration.dll
   at System.Windows.Forms.Integration.WindowsFormsHost.set_Child(Control value)
   at HomeSecurity.MainWindow..ctor() w c:\Users\R\Documents\Visual Studio 2013\Projects\HomeSecurity\HomeSecurity\MainWindow.xaml.cs:row 26
'HomeSecurity.vshost.exe' (CLR v4.0.30319: HomeSecurity.vshost.exe): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\UIAutomationTypes\v4.0_4.0.0.0__31bf3856ad364e35\UIAutomationTypes.dll'. Symbols loaded.

这是MainWindow的结构。类VideoStream扩展了类Form

      public MainWindow() {
           InitializeComponent();
           VideoStream VideoStream = new VideoStream();//creating a Form containing Activex control
           WindowsFormsHost Host = new WindowsFormsHost();//creating a host
           try {
               Host.Child = VideoStream;//setting content of Host, CAUSES THE EXCEPTION PRINTED ABOVE
           }catch(Exception e){
               Console.WriteLine(e.StackTrace);//output above
           }
        }

我无法长时间处理它,我没有时间了。如何解决这个问题?

2 个答案:

答案 0 :(得分:12)

好吧,你不能在其中添加Form(TopLevelControl)。你必须先把它作为儿童控制。设置TopLevel设置为false应使其正常工作。

VideoStream.TopLevel = false;

注意:不仅使用WindowsFormsHost,即使使用Winforms应用程序,也无法在Form内添加Form,除非TopLevel设置为false。

答案 1 :(得分:2)

为什么不从UserControl而不是VideoStream派生Form? IMO,它更适合在WPF应用程序中重用和托管它,问题就不复存在了。

[已编辑] 您应首先将WindowsFormsHost控件添加到WPF窗口,然后将UserControl派生的VideoStream控件添加到{{1控制:

WindowsFormsHost

您可以对XAML执行相同的操作:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms.Integration;

namespace WpfWinformsTest
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            // add a grid first (optional)
            var grid = new Grid();
            this.Content = grid;

            // create and add a WinForms host
            WindowsFormsHost host = new WindowsFormsHost(); 
            grid.Children.Add(host);

            // add a WinForms user control
            var videoStream = new VideoStream();
            host.Child = videoStream;
        }
    }
}

以下是<Window x:Class="WpfWinformsTest.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms" xmlns:local="clr-namespace:WpfWinformsTest" Title="MainWindow" Height="350" Width="525"> <Grid> <WindowsFormsHost Name="wfHost" Focusable="True" Margin="10,10,10,10"> <local:VideoStream x:Name="videoStream" /> </WindowsFormsHost> </Grid> </Window> 的外观(当然,您可以使用VS Designer向其中添加VideoStream等控件,而不是手动执行此操作):

axVideoPlayer

我建议你阅读以下文章:

Walkthrough: Hosting a Windows Forms Composite Control in WPF

Walkthrough: Hosting an ActiveX Control in WPF