Search code examples
c#wpfwinformswindowsformshost

WindowsFormsHost layout issue


I have embedded a Windows Forms application in a WPF browser application using WindowsFormsHost control, and the size of the form always comes a bit short (about 10px). During debug I noticed that the form height and width is 10 pixels less than the actual form height and width. So I tried manually setting the height and the width by adding 10px to the mainForm.Width and mainForm.Height but then it cuts off the edges and makes it worse. Is there a different way to set the actual width/height?

WindowsFormsHost windowsFormsHost = new WindowsFormsHost();
        //stackPanel.Width = mainForm.Width;
        //stackPanel.Height = mainForm.Height;
        //windowsFormsHost.Width = mainForm.Width;
        //windowsFormsHost.Height = mainForm.Height;
        mainForm.TopLevel = false;
        windowsFormsHost.Child = mainForm;
        stackPanel.Children.Add(windowsFormsHost);

Here is the XAML code:

<Page x:Class="WPFHost.Page1"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"
      Title="Page1">
    <Grid>
        <StackPanel Margin="0,0,10,10" Name="stackPanel" 
           HorizontalAlignment="Left" VerticalAlignment="Top" />
    </Grid>
</Page>

Screenshots:

The actual form:

enter image description here

How it is displayed on WPF

enter image description here


Solution

  • I think the problem is with your Margin. You're decreasing it by 10px in the margin, and then you increase the height and width of both Stackpanel and WindowsFormsHost. But due to Margin this manually setting of height and width doesn't effect on the StackPanel and only increases the size of the WindowsFormsHost and it goes out of the edges.

    I marked the margin by Red Color:

    enter image description here

    Just remove the margin or set it to zero:

    <StackPanel Margin="0" Name="stackPanel" 
               HorizontalAlignment="Left" VerticalAlignment="Top" />
    

    Also set the Height and Width in C# (they'll effect now):

    WindowsFormsHost windowsFormsHost = new WindowsFormsHost();
    
    stackPanel.Width = mainForm.Width;
    stackPanel.Height = mainForm.Height;
    
    windowsFormsHost.Width = mainForm.Width;
    windowsFormsHost.Height = mainForm.Height;