How to: Set a Background Image on a Form

[This documentation is for preview only, and is subject to change in later releases. Blank topics are included as placeholders.]

You can override the form's OnPaint method to draw an image as the background for your form.

To draw a background image on a form

  1. Override the form's OnPaint method

  2. Get the image from an external file on the device or as an embedded resource in the assembly.

  3. Use the Graphics object from the Graphics property of the PaintEventArgs to draw the image. Use the dimensions specified by the form's ClientRectangle property

Example

This example uses an image file compiled as an embedded resource as the background image for a form. After you add the background image to the project in Visual Studio, you must set its Build Action property to Embedded Resource in Solution Explorer.

Note

Alternatively, you can include the image as a project resource in Visual Studio and refer to the resource by name in your code. For more information, see Adding and Editing Resources (Visual C#) or How to: Retrieve Image Resources in Visual Basic.

Protected Overrides Sub OnPaint(e As PaintEventArgs)

    ' For an image added as a project resource in Visual Studio,
    ' get the resource by name:
    ' Bitmap backgroundImage = My.Resources.mypicture; 
    ' Otherwise, get the image compiled as an embedded resource.
    Dim asm As Assembly = Assembly.GetExecutingAssembly()
    Dim backGroundImage As New Bitmap(asm.GetManifestResourceStream("mypicture.bmp"))

    e.Graphics.DrawImage(backgroundImage, Me.ClientRectangle, _
        New Rectangle(0, 0, backgroundImage.Width, backgroundImage.Height), _
        GraphicsUnit.Pixel)

End Sub   
protected override void OnPaint(PaintEventArgs e)
{
    // For an image added as a project resource in Visual Studio,
    // get the resource by name:
    // Bitmap backgroundImage = Properties.Resources.mypicture; 
    // Otherwise, get the image compiled as an embedded resource.
    Assembly asm = Assembly.GetExecutingAssembly();
    Bitmap backgroundImage = new Bitmap(asm.GetManifestResourceStream("mypicture.jpg"));

    e.Graphics.DrawImage(backgroundImage, this.ClientRectangle,
        new Rectangle(0,0, backgroundImage.Width, backgroundImage.Height),
        GraphicsUnit.Pixel);
}

Compiling the Code

This example requires references to the following namespaces:

See Also

Concepts

Custom Control Development

Other Resources

Windows Forms Controls in the .NET Compact Framework