Stretched MDI Background Image in VB.Net
Here's a simple example showing how to paint an image across the background of an MDI container form stretching the image to fill the whole form width and height. Normally, if you just set the background image property of the MDI form, you will get the image tiled at its original size multiple times across the form. Using the method shown below, the image will stretch itself larger or smaller to fit the entire size of the form.
- Add a picture box to the MDI form. I've called mine pbBackground.
- Add the following code to the MDI form load event:
' Get the mdiclient area control to paint the background for us For Each c As Control In Me.Controls If TypeOf c Is MdiClient Then AddHandler c.Paint, AddressOf myMdiControlPaint AddHandler c.SizeChanged, AddressOf myMdiControlResize Exit For End If Next
- Add the following two functions:
Private Sub myMdiControlPaint(ByVal sender As Object, _ ByVal e As System.Windows.Forms.PaintEventArgs) e.Graphics.DrawImage(Me.pbBackground.Image, 0, 0, Me.Width, Me.Height) End Sub Private Sub myMdiControlResize(ByVal sender As Object, _ ByVal e As System.EventArgs) CType(sender, MdiClient).Invalidate() End Sub
If you wanted to centre the image, or amend the size so it scales but does not lose its original aspect ratio, you can easily do that in the myMdiControlPaint function. The last 4 parameters of the DrawImage function are top, left, width and height, respectively.
If you use a PNG format file, you can include transparency in the image that will show the background colour of the form through. I've used this so you can still change the background colour of the form, but have a transparent company logo in the corner, like a watermark.
You will some get flickering when the form is redrawn or resized using the method shown above. I haven't found a way round this yet...