首页 > 解决方案 > 在 WPF 网格中托管 Windows 窗体

问题描述

存在三种不同的窗体应用程序项目。我决定将它们合并到一个 wpf 表单应用程序中。因为我认为我能够在 wpf XAML 部分表单中的网格中显示表单,如下所示。

    <Grid  x:Name="winform"  Grid.Column="1">
    </Grid>

为了在 wpf 中托管 Windows 窗体应用程序,可以使用WindowsFormsHost,但在这种情况下,我将使用窗体而不是窗体控件。

为了做到这一点,首先我为每个 Windows 窗体项目和项目窗体声明三个主机作为全局变量。

      System.Windows.Forms.Integration.WindowsFormsHost host;
      System.Windows.Forms.Integration.WindowsFormsHost host1;
      System.Windows.Forms.Integration.WindowsFormsHost host2;

      Project1.Form            form;
      Project2.Form            form1;
      Project3.Form            form2;

在 wpf 主窗口加载事件中,我实例化了全局变量。

    private void MetroWindow_Loaded(object sender, RoutedEventArgs e)
    {
        host = new System.Windows.Forms.Integration.WindowsFormsHost();
        host.Name = "Form";

        host1 = new System.Windows.Forms.Integration.WindowsFormsHost();
        host1.Name = "Form1";

        host2 = new frm.Integration.WindowsFormsHost();
        host2.Name = "Form2";

        form = new Project1.Form();
        form1 = new Project2.Form();
        form2 = new Project3.Form();
     }

应用程序逻辑很简单,三个按钮分别与三个项目相关联。每个按钮绑定一个功能,如下所示。在下面的函数中,由于每个表单具有不同的宽度和高度,我将表单大小与 wpf mainwindows 大小相等。

然后将主机添加为网格中的子项。如果网格没有孩子添加点击的孩子如果网格有孩子删除孩子然后添加点击的孩子(表单)

    public void ShowProject2Form()
    {
        form1.TopLevel = false;
        form1.ControlBox = false;

        winform.Width = form1.Width + 100;
        winform.Height = form1.Height + 100;

        Application.Current.MainWindow.Height = winform.Height;
        Application.Current.MainWindow.Width = winform.Width + 100;

        form1.ControlBox = false;
        host1.Width = form1.Width + 100;
        host1.Height = form1.Height;


        if (winform.Children.Count == 0)
        {
            host1.Child = form1;
            winform.Children.Add(host1);                                
            winform.UpdateLayout();
        }
        else
        {
            if ((winform.Children[0] as WindowsFormsHost).Name == "Form2")
            {
                winform.Children.Remove(host2);
            }
            else if ((winform.Children[0] as WindowsFormsHost).Name == "Form")
            {
                winform.Children.Remove(host);
            }
            else
                winform.Children.Remove(host1);

            winform.UpdateLayout();
        }
    }

但问题是在将主机添加到网格时。执行程序后,当我将表单应用程序执行声明为类库而不是 Windows 应用程序时,会立即出现一个空白的阴影表单。除了在任务管理器中,它们还算作一个进程。这可能是什么原因?

在此处输入图像描述

标签: c#wpfwinformswindowsformshost

解决方案


推荐阅读