【问题标题】:Transparency for windows forms textboxWindows窗体文本框的透明度
【发布时间】:2013-04-09 15:17:58
【问题描述】:

我在 C# 中使用 Windows 窗体,我需要使文本框的背景颜色透明。我有一个从 0 到 255 的轨迹栏,应该可以控制它,但我遇到了一些麻烦。我今天早些时候创建了一个问题,提出了完全相同的问题,但没有成功。

这是我目前拥有的代码:

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
}

问题是绝对没有任何反应。关于为什么这不起作用的任何想法?

在上一个问题中,这位好人说了一些关于SetStyle(ControlStyles.SupportsTransparentBackColor, true); 的事情,但我不知道该放在哪里。

【问题讨论】:

  • 这篇文章已有 6 年 7 个月的历史,这说明这个问题仍然存在,因为我偶然发现了这个帖子。不幸的是,我不仅为文本框(我从上面 Patrick D'Souza 描述的 TextBox 派生)实现了这一点,而且认为它可能同样适用于 Label。结果是文本框不透明,其中一些默认恢复为系统字体,但只有在编辑时才可见。标签不仅透明而且不可见,包括标签中的文字。对不起 - 不工作。 (使用4.6客户端平台,应该有r

标签: c# winforms textbox transparency alpha


【解决方案1】:

你需要尝试这样的事情。

添加一个新的用户控件,比如 CustomTextBox 并更改

public partial class CustomTextBox : UserControl

public partial class CustomTextBox : TextBox

然后您将收到以下错误消息,指出未定义“AutoScaleMode”。删除 Designer.cs 类中的以下行。

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

对新添加的控件的构造函数进行如下更改。

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

构建,关闭自定义控件设计器(如果打开),您将能够在任何其他控件或表单上使用此控件。

如下图所示从工具箱中删除

【讨论】:

  • 此代码似乎不起作用。我放在测试表单上的这个控件的实例根本不透明。
  • 我知道这个帖子有点老了,但我有几个问题。我有控制工作,但文本的背景是白色的,当我点击一个按钮后,所有的文本都会消失,直到我再次开始输入。有没有办法解决这两个问题?
  • 我还发现了另一个问题,如果它滚动,背景就会变得非常糟糕。我不应该让它多行吗?
  • @PatrickD'Souza - 实施您的解决方案时,文本样式停止应用并且文本未显示在文本框中,前颜色和字体大小也不适用。
  • 文本框中的 UserPaint 不能很好地工作。
【解决方案2】:

创建一个继承自 TextBox 的新控件,在构造函数中设置样式以允许透明。然后使用您的新控件而不是 TextBox

在您的构造函数中执行此操作:

this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);

这将使您的新控件具有透明的背景颜色。

您可以在此处阅读有关控件样式的更多信息; MSDN: Control Styles,这也可能有所帮助; Inheriting from a Windows Forms Control with Visual C#

【讨论】:

  • Create a new control which inherits from Textbox,这与我在上一个问题中遇到的问题完全相同,我不知道该怎么做。还有,in your constructor,原谅我的无知,但我不知道它在哪里。
  • 这对我不起作用我正在以编程方式构建 GUI 元素。我在继承自文本框的自定义类的构造函数中尝试了此操作,然后尝试设置 _txtbx.BackColor = Color.Transparent; 我不再从文本框设置为透明时收到错误,但它仍然出现白色背景。
【解决方案3】:

我从不喜欢为此制作自己的继承控件。所以我为私有 SetStyle 函数做了一个包装函数。

尝试使用它而不是创建自己的类?

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);

【讨论】:

  • 你怎么称呼它?
  • 和其他功能一样吗? bool itWorked = SetStyle(myControl, ControlStyles.SupportsTransparentBackColor, true);
【解决方案4】:

很抱歉发现旧帖子,但是,现在一直在寻找几天来找到解决这个可怕的文本框不透明问题的解决方案!!! (令人惊讶的是,MSAccess 有一个检查状态来显示透明度!)

无论如何,我已经构建了一个 VB 解决方法,但是,它非常粗糙,虽然可能对很多人有所帮助,但也希望来自更核心的人的任何见解......

它基本上使用文本框,然后调整它的大小并用标签替换(因此现在代表一个透明的“出现”文本框。还有其他一些事情,比如在单行文本框上按 enter 时停止蜂鸣声。

要使用 - 创建一个新类并将所有代码粘贴到顶部,这应该会创建两个自定义对象( CTextBox 和 CLabel ) - 您只需在表单设计中使用 CTEXTBOX。

很容易转换成 C,如果那是你的语言,但如果有任何建议,请告诉我?

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

【讨论】:

    【解决方案5】:

    就这一行,它非常适合我!

    textBox1.BackColor = this.BackColor;
    

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

    【讨论】:

    • 如果文本框覆盖在图像上,这不是一个有用的解决方案。
    【解决方案6】:
    this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
    

    【讨论】:

    • 与其只是发布代码,不如解释一下为什么您的代码可以解决问题。理想情况下,您还会解释为什么您的答案与现有答案不同/更好。
    猜你喜欢
    • 1970-01-01
    • 2011-05-06
    • 2011-01-03
    • 1970-01-01
    • 2018-12-03
    • 1970-01-01
    • 2016-03-23
    • 1970-01-01
    • 2021-05-20
    相关资源
    最近更新 更多