Windows CE – building a transparent picturebox

Surprise!  PictureBox in Windows CE doesn’t support transparency.

Diving into yet another old forgotten corner of the .NET compact framework.

And just in case the mention of Compact Framework hasn’t scared you to death, today’s code will be in Visual Basic .NET

 

Imports System.Drawing.Imaging
Imports System.ComponentModel

Public Class TransparentPictureBox
    Inherits PictureBox

    Private _transparentColor As Color = Color.White
    Public Property TransparentColor() As Color
        Get
            Return _transparentColor
        End Get
        Set(ByVal value As Color)
            _transparentColor = value
        End Set
    End Property

    Protected Overloads Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)

        If Not Me.Image Is Nothing Then
            Dim pictureBounds As New Rectangle(0, 0, Me.Width, Me.Height)
            Dim imageBounds As New Rectangle(0, 0, Me.Image.Width, Me.Image.Height)
            Dim attributes As New ImageAttributes()
            ' set color to be set to transparent - if you don't paint the background below, then these pixels
            ' will appear black
            attributes.SetColorKey(Me.TransparentColor, Me.TransparentColor)
            e.Graphics.DrawImage(Me.Image, pictureBounds, imageBounds.X, imageBounds.Y, imageBounds.Width, imageBounds.Height, GraphicsUnit.Pixel, attributes)
        End If

    End Sub

    Protected Overloads Overrides Sub OnPaintBackground(ByVal e As System.Windows.Forms.PaintEventArgs)
        ' paint background color
        Dim brush As SolidBrush
        brush = New SolidBrush(Me.Parent.BackColor)
        e.Graphics.FillRectangle(brush, Me.ClientRectangle)
    End Sub

End Class