C# WinForms 标签不想透明的原因是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/605920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 10:05:01  来源:igfitidea点击:

Reasons for why a WinForms label does not want to be transparent?

c#winformstransparency

提问by Svish

Why can't I set the BackColor of a Label to Transparent? I have done it before, but now it just don't want to...

为什么我不能将标签的背景色设置为透明?我以前做过,但现在它只是不想...

I created a new UserControl, added a progressbar and a label to it. When I set the BackColor of the label to transparent it is still gray =/ Why is this?

我创建了一个新的 UserControl,为其添加了一个进度条和一个标签。当我将标签的 BackColor 设置为透明时,它仍然是灰色的 =/ 为什么会这样?

What I wanted was to have the label on top of the progressbar so that its text was "in" the progressbar...

我想要的是将标签放在进度条的顶部,以便其文本“在”进度条中......

采纳答案by Rune Grimstad

WinForms doesn't really support transparent controls, but you can make a transparent control yourself. See my answer here.

WinForms 并不真正支持透明控件,但您可以自己制作透明控件。在这里看到我的答案

In your case you should probably subclass the progress bar and override the OnPaint method to draw a text on the progress bar.

在您的情况下,您可能应该将进度条子类化并覆盖 OnPaint 方法以在进度条上绘制文本。

回答by thmsn

So as the comment to my previous answer stated, Control is the default behaviour, and is what I remembered as being Transparent.

因此,正如对我之前回答的评论所述,控制是默认行为,并且我记得它是透明的。

Anyway, have you tried setting the background property of your UserControl, or the container your label is in (Panel, Form, whatever?), your label should reflect that color :)

无论如何,您是否尝试过设置 UserControl 的背景属性或标签所在的容器(面板、表单等等?),您的标签应该反映该颜色:)



Old Answer: Its been a while since I did winforms programming, but as I recall labels are transparent per default? thus its only the text that gets an actual color and the bacground color mimics whatever is behind it :)

旧答案:我已经有一段时间没有进行 winforms 编程了,但我记得标签默认是透明的?因此,它只有获得实际颜色的文本,而背景颜色模仿了它后面的任何内容:)

回答by はると

If you want to focus on designing your windows application, I suggest you use WPF.

如果你想专注于设计你的 windows 应用程序,我建议你使用 WPF。

Making controles transparent in WPF is very easy.

在 WPF 中使控件透明非常容易。

<TextBox Width="200" Height="40" Opacity="0.5"/>

回答by Hans Passant

Add a new class to your project and post the code shown below. Build. Drop the new control from the top of the toolbox onto your form.

向您的项目添加一个新类并发布如下所示的代码。建造。将新控件从工具箱顶部拖放到表单上。

using System;
using System.Windows.Forms;

public class TransparentLabel : Label {
  public TransparentLabel() {
    this.SetStyle(ControlStyles.Opaque, true);
    this.SetStyle(ControlStyles.OptimizedDoubleBuffer, false);
  }
  protected override CreateParams CreateParams {
    get {
      CreateParams parms = base.CreateParams;
      parms.ExStyle |= 0x20;  // Turn on WS_EX_TRANSPARENT
      return parms;
    }
  }
}

回答by MaciekTalaska

It is possible to do exactly what you want to achieve. It just takes a little time to play with controls. It is possible to create a Label control with transparent background, and place it on top of Progressbar control.

完全可以做到您想要实现的目标。玩控件只需要一点时间。可以创建一个具有透明背景的 Label 控件,并将其放置在 Progressbar 控件的顶部。

Check my answer toanother SO question.

检查我对另一个 SO 问题的回答。

回答by lincolnk

as to an explanation for your problem, windows doesn't do transparency for background controls like you'd expect-i'm guessing the gray background is actually the form's surface. whatever controls are drawn between the form surface and your label are ignored.

至于对您的问题的解释,Windows 不会像您期望的那样对背景控件进行透明处理 - 我猜灰色背景实际上是表单的表面。在表单表面和您的标签之间绘制的任何控件都将被忽略。

回答by Steve

Select BackColor, go the Web tab, and select Transparent. Generates the following.

选择BackColor,转到 Web 选项卡,然后选择透明。生成以下内容。

        this.label1.BackColor = System.Drawing.Color.Transparent;

回答by BlueRaja - Danny Pflughoeft

Here is a transparent control I wrote a while ago which displays rotated text. Most of the code comes from here, though IIRC I had to make a few tweaks to get it to work.

这是我前一段时间写的一个透明控件,它显示旋转的文本。大多数代码来自这里,尽管 IIRC 我不得不做一些调整才能让它工作。

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Linq;
using System.Windows.Forms;

namespace MyNamespace
{
    public partial class RotatedText : UserControl
    {
        private readonly Timer _invalidationTimer;
        private const int WS_EX_TRANSPARENT = 0x00000020;

        public RotatedText()
        {
            this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            InitializeComponent();

            _invalidationTimer = new Timer {Interval = 500, Enabled = true};
            _invalidationTimer.Tick += TickHandler;
        }

        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        [Category("Appearance")]
        [Description("Text which appears in control")]
        public string Text { get; set; }

        #region Transparent background
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= WS_EX_TRANSPARENT;
                return cp;
            }
        }

        private void TickHandler(object sender, EventArgs e)
        {
            InvalidateEx();
        }

        private void InvalidateEx()
        {
            if (Parent != null)
                Parent.Invalidate(Bounds, false);
            else
                Invalidate();
        }

        protected override void OnPaintBackground(PaintEventArgs e)
        {
            //Intentionally do nothing - stops background from drawing
            //base.OnPaintBackground(e);
        } 
        #endregion

        //Rotate text and draw
        protected override void OnPaint(PaintEventArgs e)
        {
            double angleRadians = Math.Atan2(Height, Width);
            float angleDegrees = -1*(float) (angleRadians*180/Math.PI);
            angleDegrees *= 0.9f;
            e.Graphics.RotateTransform(angleDegrees, MatrixOrder.Append);
            e.Graphics.TranslateTransform(20, Height - 75, MatrixOrder.Append);
            e.Graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
            Font font = new Font("Ariel", 50);
            e.Graphics.DrawString(Text, font, Brushes.Gray, 1, 2); //Shadow
            e.Graphics.DrawString(Text, font, Brushes.Red, 0, 0);
        }
    }
}

回答by alexander willemse

Use a LinkLabel not a normal Label

使用 LinkLabel 而不是普通标签

    private void MakeTransparentLabel(System.Windows.Forms.LinkLabel LinkLabel)
    {
        this.MakeTransparentLabel(LinkLabel, Color.White);
    }
    private void MakeTransparentLabel(System.Windows.Forms.LinkLabel LinkLabel, Color ForeColor)
    {
        LinkLabel.ForeColor = ForeColor;
        LinkLabel.LinkColor = ForeColor;
        LinkLabel.VisitedLinkColor = ForeColor;
        LinkLabel.ActiveLinkColor = ForeColor;
        LinkLabel.DisabledLinkColor = ForeColor;
        LinkLabel.LinkArea = new LinkArea(0, 0);
        LinkLabel.LinkBehavior = LinkBehavior.NeverUnderline;
        LinkLabel.Cursor = Cursors.Arrow;
        LinkLabel.BackColor = Color.Transparent;
    }
    private void SetTransparentLabelText(System.Windows.Forms.LinkLabel LinkLabel, string Text)
    {
        if (string.IsNullOrEmpty(Text)) { LinkLabel.Text = " "; return; }
        LinkLabel.Text = Text;
    }

回答by truthseeker

Most simple solution is following:

最简单的解决方案如下:

  1. Set background color to transparency either in visual editor or in constructor of your form:

    this.label1.BackColor = System.Drawing.Color.Transparent;

  2. Set Parent property of your label to control that you want to be visible behind the text. This can be done in form constructor or in Load method:

    this.label1.Parent = progressBar1;

  1. 在可视化编辑器或表单的构造函数中将背景颜色设置为透明:

    this.label1.BackColor = System.Drawing.Color.Transparent;

  2. 设置标签的 Parent 属性以控制您希望在文本后面可见。这可以在表单构造函数或 Load 方法中完成:

    this.label1.Parent = progressBar1;

Its true that this is not true transparency as in DirectX. The result you see on display is composed only from two layers. You cant sum up more than two layers with this approach (each layer having its own transparency defined by alpha parameter). But its suitable for many practical situations you can encounter in Winforms programming.

确实,这不是 DirectX 中真正的透明度。您在显示器上看到的结果仅由两层组成。您不能用这种方法总结两个以上的图层(每个图层都有自己由 alpha 参数定义的透明度)。但它适用于您在 Winforms 编程中可能遇到的许多实际情况。