Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

c# - Transparency for windows forms textbox

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...