Backgrounds
Up
Tired of boring backgrounds? Here are three ways of incorporating pictures into the background of your form for any project. Try each one!

Method 1: Simple picture

Simply load a picture file into the picture property of the form or paste a previously copied picture into it (from the clipboard). This method is OK if the form has a fixed size (because the form's Borderstyle property is set to 'fixed single') but not good on a resizable form because if the form is made bigger than the picture it won't look good.

Method 2: Stretched Picture

This method will stretch a picture to fill the form exactly, no matter how big or small the form is made. It's a good method to use with abstract pictures and resizable forms, but not good for pictures that will look distorted if they are stretched in one dimension and not the other.

Put an image control on your form and name it imgBack. Copy one of the pictures below into the image control's picture property or use one of your own. Set the stretch property of the image control to true and set both the left and top properties of the image control to zero, so that the image control is in the top-left corner of the form. Then add this code:

Private Sub Form_Resize()
imgBack.Width = Me.Width
imgBack.Height = Me.Height
End Sub

This is easy to understand, as long as you know that 'Me' is another way of referring to the form, without having to mention its name. Try it!

  

Method 3: 

Choose one of the pictures above (or a picture of your own), then copy it and paste it into the picture property of a picturebox called picTile that you have added to your project (set the visible property of the picturebox to false and its autosize property to true). Then just add the following code to your project and Presto... a beautiful tiled background. The real beauty, of course, is in the code - can you figure out how it works?

Private Sub Form_Resize()
Me.AutoRedraw = True
For X = 0 To Me.ScaleWidth Step picTile.Width
	For Y = 0 To Me.ScaleHeight Step picTile.Height
		Me.PaintPicture picTile.Picture, X, Y, _
		picTile.Width, picTile.Height
	Next Y
Next X
End Sub

Note that:

bullet'Me' in the above code refers to the form, no matter what name the form may have.
bulletThe line that ends with a space and an underscore character ' _' continues on the next line - it is ALL ONE LINE. This trick is used to 'wrap' long lines of code to make them easier to read.

The code works by using a loop within a loop (the loops are said to be 'nested'). The outer loop steps across the width of the form with a step size equal to the width of the picturebox. The inner loop steps down the form. Within the inner loop is an instruction for painting a copy of the picture onto the form at the coordinates x and y defined by the two loops. Thus copies of the picture are painted repeatedly onto the form until the whole form is covered.

To understand the function of the autoredraw statement check the VB help system.

Previous Up Next