Setting MdiParent Background Image properly

10,376

Solution 1

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

this points to Form.

Myself too noticed the same behavior you mentioned. It seems just a painting issue. Add the following code to fix it.

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

Solution 2

The MdiClient.BackgroundImageLayout is not relevant for the class MdiClient (as stated by the MSDN document page). You should try some work-around. One of the work-around is paint the BackgroundImage yourself:

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);
Share:
10,376
Durga
Author by

Durga

Updated on June 18, 2022

Comments

  • Durga
    Durga almost 2 years

    I am using below code to set background image of MdiParent form ,and it is working well ,but when I click on maximize button than BackgroundImage is repeating at rightside and bottom edge(i.e right side and bottom side Image portion is repeating) ,how do I avoid this and display Image properly ?

    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;
            }
        }
    }
    
  • Sriram Sakthivel
    Sriram Sakthivel over 10 years
    @Durga Updated my answer
  • user1703401
    user1703401 over 10 years
    The image needs to be disposed.
  • King King
    King King over 10 years
    @HansPassant thank you, I'm not sure how it should be done to dispose the image. Could you review my updated code?
  • Nathan F.
    Nathan F. over 8 years
    @HansPassant The image is being disposed. The "using" statement disposes of the object once it's finished running