tags:

views:

116

answers:

1

This is a followup to this SO question: How do I make a collapsible UI region on the form?


I'm making a winforms app with a region (panel) that is expandable or collapsible.

I used the expand/collapse bitmaps from the VS2008 Image library, for the buttons. I put those two into an ImageList.

I wanted the button to have no border, so I set FlatStyle = Flat, FlatAppearance.BorderSize = 0.

On the click event for the button, I have

private void button1_Click(object sender, EventArgs e)
{
    if (splitContainer1.Panel1Collapsed == true)
    {
        splitContainer1.Panel1Collapsed = false;
        button1.ImageIndex = 0;
        this.toolTip1.SetToolTip(this.button1, "Collapse");
    }
    else
    {
        splitContainer1.Panel1Collapsed = true;
        button1.ImageIndex = 1;
        this.toolTip1.SetToolTip(this.button1, "Expand");
    }
}

But the transparency in the bitmap is not respected. My understanding was that the color used in the top-left (or is it bottom-left?) corner of the bitmap will be treated as transparent, so when the bitmap is displayed, any pixels with that same color value will be transparent. But I don't get those results. Instead I get the transparent color to show up as its true color.

alt text alt text

I found a way to avoid this by providing an OnPaint method for the button, and manually drawing the bmp after calling MakeTransparent() on it, like this:

private void button1_Paint(object sender, PaintEventArgs e)
{
    // This draws the image on the button, and makes the bmp
    // background color as transparent. Why this isn't done
    // automatically, I don't know. 
    Bitmap bmp = (Bitmap) imageList1.Images[button1.ImageIndex];
    bmp.MakeTransparent();
    int x = (button1.Width - bmp.Width) / 2;
    int y = (button1.Height - bmp.Height) / 2;
    e.Graphics.DrawImage(bmp, x, y);
}

But isn't there a simpler way?

+1  A: 

You need to set the TransparentColor property on the ImageList.

Pete McKinney
What if I don't know what the color is? Isn't there a convention that the corner pixel indicates the transparent color? Is there a way for me to just say - whatever color is in the corner of the bitmap - use THAT. BitMap.MakeTransparent() makes "the system default transparent color" as transparent for that bitmap. Is there a way for me to set THAT?
Cheeso
I just set TransparentColor to Fuschia, and it worked. Also, I had to set the image size to 12x12, rather than 16x16 (the bitmap size), because the button was getting a 16x16 shadow when I hovered. When I set the TransparentColor and shrank the image size (not the size on the ImageList), I did not need the button1_Paint() method. Thanks for the tip.
Cheeso