[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Give transparent backgrounds to images displayed on buttons in C#

[Give transparent backgrounds to images displayed on buttons in C#]

This example shows how to give transparent backgrounds to the images displayed on a button.

If you give buttons images that have transparent backgrounds, then the button's background can show through. If the images don't have transparent backgrounds, the result are rectangular blocks sitting on top of the buttons. There are a couple of ways you can work around this.

First, you can give the images transparent backgrounds as described in the post Make a tool that creates PNG files with transparent backgrounds in C#.

[Give transparent backgrounds to images displayed on buttons in C#]Second, you can color the images' backgrounds so they match the button's backgrounds. Note that the appearance of buttons may differ in different versions of Windows so this may not work very well. For example, in the picture on the right the buttons don't have solid colored backgrounds.

This example uses the following MakeButtonTransparent method to give a buttons' images a transparent background at run time.

// Give the button a transparent background. private void MakeButtonTransparent(Button btn) { Bitmap bm = (Bitmap)btn.Image; bm.MakeTransparent(bm.GetPixel(0, 0)); }

This method gets the button's current image as a Bitmap. It calls the Bitmap object's MakeTransparent method to convert all of the pixels of a particular color into a transparent color. The color that the code converts is whatever color is in the image's upper left corner. The image is already displayed in the button so the change appears automatically.

So the procedure is to make the button's image so all of the background pixels have the same color as the pixel in the upper left corner. Then when the form loads, call MakeButtonTransparent for the button.

Note that some controls such as ToolStripButton, ToolStripSplitButton, and ToolStripMenuItem have an ImageTransparentColor property that does this for you. Simply set this property to the color of the background pixels in the image and you're all set.

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.