【问题标题】:Setting MdiParent Background Image properly正确设置 MdiParent 背景图像
【发布时间】:2018-10-10 03:18:53
【问题描述】:

我正在使用下面的代码来设置 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;
        }
    }
}

【问题讨论】:

    标签: c# winforms


    【解决方案1】:
    this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
    

    this 指向表单。

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

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

    【讨论】:

    • @Durga 更新了我的答案
    【解决方案2】:

    MdiClient.BackgroundImageLayout 与 MdiClient 类无关(如 MSDN 文档页面所述)。你应该尝试一些变通方法。解决方法之一是自己绘制 BackgroundImage:

    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);
    

    【讨论】:

    • 图片需要处理。
    • @HansPassant 谢谢,我不知道应该如何处理图像。您能查看我更新的代码吗?
    • @HansPassant 正在处理图像。 “using”语句在对象完成运行后处理它
    【解决方案3】:
    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多