Question

I know this question has been already asked quite some times, but i would like to specify it. I got an image, which displays a circle blue X and I would like to make my own exit button in a Windows application form.

To do that, i added a button in the form and loaded the image on the button. However, the backcolor of the button ruins the image as it is grey. So i have tried:

private: System::Void button1_Paint(System::Object^  sender, 
System::Windows::Forms::PaintEventArgs^  e) {

        this->TransparencyKey = BackColor;   
    }

This doesn't work at all (The backcolor is still grey). So i have tried this:

private: System::Void button1_Paint(System::Object^  sender, 
System::Windows::Forms::PaintEventArgs^  e) {

        this->BackColor = System::Drawing::Color::Transparent;
    }

Here i got a message: This control doesn't support transparent colors

Ok, so how am i gonna do this? thanks

Was it helpful?

Solution

In WPF as well as win32, controls or child windows in general can't have color transparency.

But they can have a non rectangular region. Any shape, including holes.

Use the control's region property to change it's region. There's an example in this link on how to draw a round button.

FYI, pixels that are outside the region are NOT receiving any messages/notifications.

Examples of crazy shaped controls:

  1. Button shaped like a person's head.
  2. Spiral shape.
  3. 3 triangles that do not touch each other.
  4. Chess board - every 2nd pixel is transparent.

Also, a region is dynamic, can be changed after object creation, so your button can grow and shrink...

It's also pretty fast.

Limitations:

  • No alpha blending - either opaque or fully transparent.

I wrote a function (C++/win32) that takes a control and a BMP, both have the same size, scan the BMP for a "tranparent" color (you decide which color) and remove all pixels in that color from the region of the control. This is about half a screen of code.

OTHER TIPS

Set the Background-property to Transparent:

btn->Background = System::Drawing::Color::Transparent;

By the way, don't do this in the Paint-Handler. Instead, do it in the constructor or any initialization function.

Update: Ok, got it - it's a Windows Forms application. See this C# Windows Form Application Transparent button link for some solutions for your problem.

Another possibility (that I have used in projects before) would be to use a PictureBox instead and listen to the MouseClick-event.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top