Transparency for windows forms textbox
Asked Answered
W

7

18

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.

Wandering answered 17/4, 2013 at 2:9 Comment(2)
Possible duplicates: Making a TextBox Transparent and TextBox with a Transparent BackgroundTimer
The fact that this post is 6 years 7 months old, goes to tell that this issue is still out there, for I stumbled over this thread. Unfortunately I went ahead and implemented this for not only textbox (I derived from TextBox as described by Patrick D'Souza above) but figured it may work for Label equally well. The result was that the text box was not transparent, some of them defaulted back to system font but were visible only when being edited. The labels were not only transparent but invisible, including the text in the label. Sorry - not working. (Using 4.6 Client platform, and should have rPrecinct
L
18

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

Luzluzader answered 17/4, 2013 at 3:19 Comment(7)
Sorry for my ignorance but how can you call it in your form?Megalopolis
This code doesn't seem to work. The instance of this control I've put on a test form is not transparent at all.Savona
I know this thread is kind of old, but I have a couple of questions. I have the control working, but the background of the text is white, and after I click a button, all the text goes away until I start typing again. Is there a way to fix these 2 issues?Guadalquivir
I also found another issue to where if it scrolls, the background messes up pretty bad. Should I have not made it multi line?Guadalquivir
This works only for background, but when entering text, the text box is no longer transparent.Correlative
@PatrickD'Souza - When implementing your solution the text style stopped to apply and the text is not shown in the textbox, also fore color and font size does not apply.Alehouse
UserPaint in a textbox is not going to work very well.Bruno
M
5

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#

Mallory answered 17/4, 2013 at 2:44 Comment(2)
Create a new control which inherits from Textbox, this was the exact same problem that I had in the previous question, I don't know how to. Also, in your constructor, pardon my ignorance, but I don't know where it is located.Wandering
This Does not work for me I am programmatically building the GUI elements. I tried this in the constructor of a custom class that inherits from textbox and then tried setting the _txtbx.BackColor = Color.Transparent; I no longer get an error from the textbox being set to transparent but it still comes up with a white background.Rundown
C
5

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;
            if (c != null)
            {
                Type typeTB = typeof(Control);
                System.Reflection.MethodInfo misSetStyle = typeTB.GetMethod("SetStyle", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                if (misSetStyle != null) { misSetStyle.Invoke(c, new object[] { Style, value }); retval = true; }
            }
            return retval;
        }

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

Contextual answered 19/2, 2014 at 15:47 Comment(2)
How would you call it?Colville
Just like any other function? bool itWorked = SetStyle(myControl, ControlStyles.SupportsTransparentBackColor, true);Contextual
A
1

Sorry to uncover old posts, however, been searching for a few days now to find a solution to this awful problem of no transparency for textboxes!!! (Amazingly MSAccess has a check state to show transparency!)

Anyways, I have built a VB workaround, however, it is very crude and whilst may help a lot of people would also like any input from the more hard-core'rs with any insights...

It basically uses the textbox, then sizes it away and replaces with a label (hence now representing a transparent "appearing" textbox. Also couple of other things like stopping the beeping if press enter on a single line textbox.

To use - Create a new class and paste ALL the code over the top this should create two custom objects ( CTextBox and CLabel ) - you only need to use CTEXTBOX in your form design.

Easily converts into C, if that's your language, but please let me know if have any suggestions?

Imports System.ComponentModel

Public Class CTextBox
Inherits TextBox
Dim _zUseEnterAsTab As Boolean = True
Dim _zUseTransparent As Boolean = False
Dim _zUseTransparentColor As Color = Color.Transparent
Dim _zUseTransparentBorderColor As Color = Color.Gray
<Description("Use the Enter Key as Tab (Stops Beeps) only for Single line TextBox"), Category("CTextBox")> _
Public Property zUseEnterAsTab() As Boolean
    Get
        Return _zUseEnterAsTab
    End Get
    Set(value As Boolean)
        _zUseEnterAsTab = value
        Me.Invalidate()
    End Set
End Property
<Description("Use Transparent TextBox"), Category("CTextBox")> _
    Public Property zUseTransparent() As Boolean
    Get
        Return _zUseTransparent
    End Get
    Set(value As Boolean)
        _zUseTransparent = value
        Me.Invalidate()
    End Set
End Property
<Description("Change the transparency to ANY color or shade or Alpha"), Category("CTextBox")> _
Public Property zUseTransparentColor() As Color
    Get
        Return _zUseTransparentColor
    End Get
    Set(value As Color)
        _zUseTransparentColor = value
        Me.Invalidate()
    End Set
End Property
<Description("Border color of the texbox when transparency used"), Category("CTextBox")> _
    Public Property zUseTransparentBorderColor() As Color
    Get
        Return _zUseTransparentBorderColor
    End Get
    Set(value As Color)
        _zUseTransparentBorderColor = value
        Me.Invalidate()
    End Set
End Property
Protected Overrides Sub OnCreateControl()
    'Again for my benifit - there may be other ways to force the transparency 
    'code at form / event startup, but this is the way i chose, any advice
    'or alternatives would be great!! :)
    If Not DesignMode Then
        'Basically don't do in design mode!
        If _zUseTransparent Then
            'Added to handle the event of textbox dissabled
            If Me.Enabled Then
                CreateMyLabel(Me)
                MakeLabelVisible(foundLabel, Me)
            End If
        End If
    End If
    MyBase.OnCreateControl()
End Sub
Protected Overrides Sub OnKeyPress(e As KeyPressEventArgs)
    If MyBase.Multiline = True Then
        MyBase.OnKeyPress(e)
    Else
        If e.KeyChar = Chr(Keys.Enter) Then
            e.Handled = True
            If zUseEnterAsTab = True Then SendKeys.Send("{tab}")
            MyBase.OnKeyPress(e)
        End If
    End If
End Sub
Protected Overrides Sub OnLeave(e As EventArgs)
    If _zUseTransparent Then
        CreateMyLabel(Me)
        MakeLabelVisible(foundLabel, Me)
    End If
    MyBase.OnLeave(e)
End Sub
Protected Overrides Sub OnEnter(e As EventArgs)
    If _zUseTransparent Then
        CreateMyLabel(Me)
        MakeTextBoxVisible(foundLabel, Me)
    End If
    MyBase.OnEnter(e)
End Sub
Dim foundLabel As CLabel = Nothing
Sub CreateMyLabel(_TxtBox As CTextBox)
    foundLabel = Nothing
    Dim l As CLabel
    If GetMyLabel("L_" & Me.Name, Me) Then
        l = foundLabel
        If Not l.Name = "L_" & Me.Name Then
            MsgBox("L_" & Me.Name)
        End If
        l.Font = _TxtBox.Font
        l.Text = _TxtBox.Text
        l.BorderColor = _zUseTransparentBorderColor
        l.BackColor = _zUseTransparentColor
        l.BorderStyle = Windows.Forms.BorderStyle.None 'Handled by paint event
    Else
        l = New CLabel
        l.Name = "L_" & _TxtBox.Name
        l.BorderColor = _zUseTransparentBorderColor
        l.BackColor = _zUseTransparentColor
        l.Size = _TxtBox.Size
        l.BorderStyle = Windows.Forms.BorderStyle.None 'Handled by paint event
        l.AutoSize = False
        l.Font = _TxtBox.Font
        l.Location = _TxtBox.Location
        l.Text = _TxtBox.Text
        l.Anchor = _TxtBox.Anchor
        _TxtBox.Parent.Controls.Add(l)
        foundLabel = l
    End If
End Sub
Function GetMyLabel(_LabelName As String, _TxtBox As CTextBox) As Boolean
    For Each ctl As Control In _TxtBox.Parent.Controls
        If ctl.Name = _LabelName Then
            foundLabel = ctl
            Return True
        End If
    Next
    Return False
End Function
Private Sub MakeLabelVisible(_Label As CLabel, _TxtBox As CTextBox)
    _Label.Location = _TxtBox.Location
    _Label.Anchor = _TxtBox.Anchor
    _Label.Size = _TxtBox.Size
    _TxtBox.Size = New Size(0, 0)
    _TxtBox.Anchor = AnchorStyles.None
End Sub
Private Sub MakeTextBoxVisible(_Label As CLabel, _TxtBox As CTextBox)
    _TxtBox.Location = _Label.Location
    _TxtBox.Anchor = _Label.Anchor
    _TxtBox.Size = _Label.Size
    _Label.Size = New Size(0, 0)
    _Label.Anchor = AnchorStyles.None
End Sub
End Class

Public Class CLabel
Inherits Label
Public BorderColor As Color = Color.Gray
Sub New()
    MyBase.FlatStyle = Windows.Forms.FlatStyle.Standard
    'Added padding as labels shifted text upwards
    'NOT tested on all fonts etc, purely for my sources
    MyBase.Padding = New Padding(0, 3, 0, 0)
End Sub
Protected Overrides Sub OnMouseDown(e As MouseEventArgs)
    Dim _TxtBox As CTextBox = Nothing
    Dim _TxtBoxName As String = Microsoft.VisualBasic.Right(Me.Name, Len(Me.Name) - 2)
    For Each elem As Control In Me.Parent.Controls
        If elem.Name = _TxtBoxName Then
            _TxtBox = elem
            Exit For
        End If
    Next
    _TxtBox.Select()
    MyBase.OnMouseDown(e)
End Sub
Protected Overrides Sub OnMouseEnter(e As EventArgs)
    Cursor = Cursors.IBeam
    MyBase.OnMouseEnter(e)
End Sub
Protected Overrides Sub OnMouseLeave(e As EventArgs)
    Cursor = Cursors.Default
    MyBase.OnMouseLeave(e)
End Sub
Protected Overrides Sub OnPaint(e As PaintEventArgs)
    MyBase.OnPaint(e)
    ControlPaint.DrawBorder(e.Graphics, Me.DisplayRectangle, Color.Gray, ButtonBorderStyle.Solid)
End Sub
Private Sub MakeLabelVisible(_Label As CLabel, _TxtBox As CTextBox)
    _Label.Size = _TxtBox.Size
    _TxtBox.Size = New Size(0, 0)
    _Label.Anchor = _TxtBox.Anchor
    _TxtBox.Anchor = AnchorStyles.None
End Sub
Private Sub MakeTextBoxVisible(_Label As CLabel, _TxtBox As CTextBox)
    _TxtBox.Size = _Label.Size
    _Label.Size = New Size(0, 0)
    _TxtBox.Anchor = _Label.Anchor
    _TxtBox.Anchor = AnchorStyles.None
End Sub
End Class
Anglesey answered 3/9, 2014 at 14:53 Comment(0)
A
0

Just this line and it worked for me perfectly!

textBox1.BackColor = this.BackColor;

Source: https://www.codegrepper.com/code-examples/csharp/set+textbox+colour+to+transparent+c%23

Algernon answered 27/10, 2020 at 23:31 Comment(1)
This is not a useful solution if the textbox is laid over an image.Riancho
M
0
SolidColorBrush br = new SolidColorBrush();
br.Color= Windows.UI.Color.FromArgb(0,0,0,0);
textbox.Background = br;

This worked for me after nothing else did. Don't forger to swap for your textbox's name.

Melanymelaphyre answered 19/12, 2022 at 11:6 Comment(0)
L
-3
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
Llano answered 11/12, 2015 at 1:25 Comment(1)
Rather than just posting code, it would be better if you explained why your code solves the problem. Ideally you would also explain why your answer is different/better than the existing answers.Astrolabe

© 2022 - 2025 — McMap. All rights reserved.