Friday, July 13, 2007

Setting transparent color to control's BackColor property

Using C# with .Net Framework 2.0, an attempt to assign a color from the System.Drawing.Color struct to the BackColor property of a window’s control, say a System.Windows.Forms.TextBox, will compile and run successfully.

Snippet 1:
textBox1.BackColor = Color.Cyan;

However, a problem arises when any transparent color (e.g. #00FEF2D4) is assigned to the BackColor property. Upon execution, a runtime exception will be thrown (see below).

Snippet 2:
textBox1.BackColor = ColorTranslator.FromHtml("#00FEF2D4");


On msdn, the following explanation is given:
The BackColor property does not support transparent colors unless the SupportsTransparentBackColor value of System.Windows.Forms.ControlStyles is set to true.

Using the control’s SetStyle() method, this SupportsTransparentBackColor value can be changed. The problem now is that SetStyle() is declared as a protected method and thus, only the control’s class or any child class can call this method.


A quick solution
A possible solution is to create a class inheriting from the control’s class. For example, a TransparentTextBox class can inherit from the System.Windows.Forms.TextBox. Now, the protected SetStyle() method is accessible and the SupportsTransparentBackColor value can be set to true. The ideal place to call the SetStyle() method will be in the constructor of this new class after the InitializeComponent() method calls.



It’s done. Now, as an instance of TransparentTextBox can be created and any transparent color can be set.

Snippet 3:
transparentTextBox1.BackColor = ColorTranslator.FromHtml("#00FEF2D4");

One major concern: do we really want to subclass all controls that probably will need a transparent color? Think...

4 comments:

Abdellah MOUHOU said...

Hi,
I think that your code doesn't work as the SetStyle method is not supported in the .NET compact framework.
If you have a different method to do that please keep me informed.

Thanks

ashvin said...

Hello Abdellah,

the article and the code relates to .NET 2.0 full framework.

Though I have not tried it, i would recommend you to search for the pinvoke call to achieve it in compact framework...

thanks.

Henaosinho said...

Hi,

I have the same problem: I'm using the compact framework. But I don't know what a 'pinvoke call' is... Can you help me, please.

Thanks

Henaosinho said...

Hi,

I have the same problem: I'm using the compact framework. What is the 'pinvoke call'? And how can it help me achieve my goal here?
Thanks,

Renan