Transparent ListView Control???

Ok so the ListView control does not support transparency, this I know because last week I spent a couple of hours, first trying to override it’s OnPaint method and finally frustratedly trawling the internet to find out why I could not!  Essentially the ListView control in VS is just a wrapper to the old Win32 control, meaning there’s no simple way of implementing transparency.

Being a newbie to .NET I did not want the complication of learning and using hooks to achieve the desired effect, so did what I tend to always do in situations such as these and cheated!  By creating a pixel array of the background (which has a nice gradient effect) directly behind the ListView box, I was able to create a new Bitmap and use this as the Background Image of the LV, thus giving the illusion of transparency!  Ok ok, yes it’s a cheat and yes, it’s not a very good one but hey it looks the part!

My code is as follows and is almost certainly the least optimal way of achieving this…next step is to look more closely at the Bitmap class for a neater and faster method:

private void MakeTransparent(Control ctrl, int x, int y)
{
    Bitmap bMap = new Bitmap(this.BackgroundImage);
    Color[,] pixelArray = new Color[ctrl.Width, ctrl.Height];

    for (int i = 0; i < ctrl.Width; i++)
    {
        for (int j = 0; j < ctrl.Height; j++)
        {
            pixelArray[i, j] = bMap.GetPixel(x + i, y + j);
        }
    }

    Bitmap bmp = new Bitmap(ctrl.Width, ctrl.Height);

    for (int i = 0; i < ctrl.Width; i++)
    {
        for (int j = 0; j < ctrl.Height; j++)
        {
            bmp.SetPixel(i, j, pixelArray[i, j]);
        }
    }

    ctrl.BackgroundImage = bmp;
    ctrl.Location = new Point(x, y);
}

And the result…

Advertisements