Transparency for windows forms textbox

P1C Unrelated picture P1C Unrelated · Apr 17, 2013 · Viewed 66.6k times · Source

I'm using windows forms in C# and I need to make a textbox's background color transparent. I have a trackbar that goes from 0 to 255 that is supposed to control it, but I'm having some trouble. I created a question earlier today asking the exact same thing, but no success.

Here is the code I currently have:

private void trackAlpha_ValueChanged(object sender, EventArgs e)
{
    newColor = Color.FromArgb(trackAlpha.Value, colorDialog.Color.R, colorDialog.Color.G, colorDialog.Color.B);
    colorDialog.Color = newColor; // The Windows dialog used to pick the colors
    colorPreview.BackColor = newColor; // Textbox that I'm setting the background color
}

The problem is that absolutely nothing happens. Any ideas on why this is not working?

On the previous question, this nice guy said something about SetStyle(ControlStyles.SupportsTransparentBackColor, true);, but I have no idea on where I should put this.

Answer

Patrick D'Souza picture Patrick D'Souza · Apr 17, 2013

You need to try out something like this.

Add a new user control , say CustomTextBox and change

public partial class CustomTextBox : UserControl

to

public partial class CustomTextBox : TextBox

You will then get the following error saying that the 'AutoScaleMode' is not defined. Delete the following line in the Designer.cs class.

this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;

Make changes to the constructor of your newly added control as follows.

public partial class CustomTextBox : TextBox
{
    public CustomTextBox()
    {
        InitializeComponent();
        SetStyle(ControlStyles.SupportsTransparentBackColor |
                 ControlStyles.OptimizedDoubleBuffer |
                 ControlStyles.AllPaintingInWmPaint |
                 ControlStyles.ResizeRedraw |
                 ControlStyles.UserPaint, true);
        BackColor = Color.Transparent;
    }
}

Build, close the custom control designer if open and you will be able to use this control on any other control or form.

Drop it from the toolbox as shown below enter image description here