Transparency for windows forms textbox

I never liked having to make my own inherited controls for this. So I made a wrapper function to the private SetStyle function.

Try using it instead of creating your own class?

public static bool SetStyle(Control c, ControlStyles Style, bool value)
{
    bool retval = false;
    Type typeTB = typeof(Control);
    System.Reflection.MethodInfo misSetStyle = typeTB.GetMethod("SetStyle", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
    if (misSetStyle != null && c != null) { misSetStyle.Invoke(c, new object[] { Style, value }); retval = true; }
    return retval;
}

bool itWorked = SetStyle(myControl, ControlStyles.SupportsTransparentBackColor, true);


Create a new control which inherits from TextBox, set the style to allow tranparency in the constructor. Then use your new control instead of TextBox

Do this in your constructor:

this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);

This will allow your new control to have a transparent background color.

You can read more about control styles here; MSDN: Control Styles, this may help as well; Inheriting from a Windows Forms Control with Visual C#


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