正确设置 MdiParent 背景图像

本文关键字:背景 图像 MdiParent 设置 | 更新日期: 2023-09-27 18:36:28

我正在使用以下代码来设置MdiParent表单的背景图像,并且效果很好,但是当我单击最大化按钮时,BackgroundImage在右侧和底部边缘重复(即右侧和底部图像部分重复),如何避免这种情况并正确显示图像?

public Parent()
{
    InitializeComponent();
    foreach (Control ctl in this.Controls)
    {
        if (ctl is MdiClient)
        {
            ctl.BackgroundImage = Properties.Resources.bg;
            ctl.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
            break;
        }
    }
}

正确设置 MdiParent 背景图像

this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;

this指向表单。

我自己也注意到了你提到的同样的行为。这似乎只是一个绘画问题。添加以下代码来修复它。

protected override void OnSizeChanged(EventArgs e)
{
    base.OnSizeChanged(e);
    this.Refresh();
}

MdiClient.BackgroundImageLayout 与类MdiClient无关(如 MSDN 文档页所述)。您应该尝试一些解决方法。解决方法之一是自己绘制背景图像

MdiClient client = Controls.OfType<MdiClient>().First();
client.Paint += (s, e) => {
   using(Image bg = Properties.Resources.bg){
     e.Graphics.DrawImage(bg, client.ClientRectangle);
   }
};
//Set this to repaint when the size is changed
typeof(Control).GetProperty("ResizeRedraw", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
              .SetValue(client, true, null);
//set this to prevent flicker
typeof(Control).GetProperty("DoubleBuffered", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
               .SetValue(client, true, null);
Private Sub Frmmain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Try
        For Each ctl As Control In Me.Controls
            If TypeOf ctl Is MdiClient Then
                ctl.BackgroundImage = Me.BackgroundImage
            End If
        Next ctl
        Me.BackgroundImageLayout = ImageLayout.Zoom
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

Private Sub Frmmain_SizeChanged(sender As Object, e As EventArgs) Handles MyBase.SizeChanged
    Try
        Me.Refresh()
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub