Dlaczego Etykieta WinForms nie chce być przezroczysta?

Dlaczego nie mogę ustawić koloru tła etykiety na przezroczysty? Robiłam to wcześniej, ale teraz po prostu nie chce...

Utworzyłem Nowy UserControl, dodałem do niego pasek postępu i etykietę. Kiedy ustawiam kolor tła etykiety na przezroczysty, nadal jest szary = / dlaczego tak jest?

Chciałem mieć etykietę na pasku postępu, aby jej tekst był " w " pasku postępu...

Author: John Saunders, 2009-03-03

11 answers

WinForms tak naprawdę nie obsługuje przezroczystych kontrolek, ale możesz zrobić przezroczystą kontrolę samodzielnie. zobacz moją odpowiedź tutaj .

W Twoim przypadku powinieneś podklasować pasek postępu i nadpisać metodę OnPaint, aby narysować tekst na pasku postępu.

 14
Author: Rune Grimstad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:34:18

Dodaj nową klasę do swojego projektu i dodaj kod pokazany poniżej. Buduj. Upuść nową kontrolkę z góry skrzynki narzędziowej na formularzu.

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;
    }
  }
}
 29
Author: Hans Passant,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-03-03 21:22:16

Najprostszym rozwiązaniem jest:

  1. Ustaw kolor tła na przezroczystość w edytorze wizualnym lub w konstruktorze formularza:

    To.label1./ - Bgcolor = "# Ffffff"Rysunek.Kolor.Przezroczysty;

  2. Ustaw właściwość nadrzędną etykiety, aby kontrolować, czy chcesz być widoczny za tekstem. Można to zrobić w konstruktorze formularza lub w metodzie Load:

    To.label1.Parent = progressBar1;

Its true that this is not true przezroczystość jak w DirectX. Wynik wyświetlany na wyświetlaczu składa się tylko z dwóch warstw. Dzięki temu podejściu nie można zsumować więcej niż dwóch warstw (każda warstwa ma własną przezroczystość zdefiniowaną przez parametr Alfa). Ale nadaje się do wielu praktycznych sytuacji, które można napotkać w programowaniu Winforms.

 6
Author: truthseeker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-09 07:33:12

Użyj LinkLabel, a nie zwykłej etykiety

    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;
    }
 4
Author: alexander willemse,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-03-25 21:50:48

Jeśli chcesz skupić się na projektowaniu aplikacji windows, proponuję użyć WPF.

Uczynienie kontrolek przezroczystymi w WPF jest bardzo proste.

<TextBox Width="200" Height="40" Opacity="0.5"/>
 1
Author: はると,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-03-03 11:13:29

Oto przezroczysta kontrolka, którą napisałem jakiś czas temu, która wyświetla obrócony tekst. Większość kodu pochodzi z Tutaj , chociaż IIRC musiałem wprowadzić kilka poprawek, aby go uruchomić.

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);
        }
    }
}
 1
Author: BlueRaja - Danny Pflughoeft,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-05-26 14:54:54

Jest to bardzo proste rozwiązanie i działa świetnie:

public class MyLabel : Label
{
    private bool fTransparent = false;
    public bool Transparent
    {
        get { return fTransparent; }
        set { fTransparent = value; }
    }
    public MyLabel() : base()
    {
    }
    protected override CreateParams CreateParams
    {
        get
        {
            if (fTransparent)
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x00000020; //WS_EX_TRANSPARENT
                return cp;
            }
            else return base.CreateParams;
        }
    }
    protected override void WndProc(ref Message m)
    {
        if (fTransparent)
        {
            if (m.Msg != 0x14 /*WM_ERASEBKGND*/ && m.Msg != 0x0F /*WM_PAINT*/)
                base.WndProc(ref m);
            else 
            {
                if (m.Msg == 0x0F) // WM_PAINT
                    base.OnPaint(new PaintEventArgs(Graphics.FromHwnd(Handle), ClientRectangle));
                DefWndProc(ref m);
            }
        }
        else base.WndProc(ref m);
    }
}

Gdy label backcolor jest przezroczysty, wtedy label robi tylko obraz swojej podstawowej kontrolki za pierwszym razem, gdy jest tworzona, po tym, jak kolor backcolor etykiety jest stały. Za każdym razem, gdy etykieta się przemalowuje, przemalowuje się do ustalonego koloru lub wzoru.

Nadpisanie CreateParams wpływa na sposób utworzenia okna do sterowania, co umożliwia rzeczywistą przezroczystość.

Overriving WndProc you control which wiadomości powinny być przekazywane do klasy bazowej. Musimy filtrować WM_ERASEBKGND i WM_PAINT, ale musimy również wywołać zdarzenie paint.

 1
Author: Elvedin Hamzagic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-12 10:54:56

Tak jak w komentarzu do mojej poprzedniej odpowiedzi stwierdzono, kontrola jest domyślnym zachowaniem i jest tym, co zapamiętałem jako przezroczyste.

W każdym razie, próbowałeś ustawić właściwość tła UserControl lub kontenera, w którym znajduje się Twoja Etykieta (Panel, formularz, cokolwiek?), etykieta powinna odzwierciedlać ten kolor:)


Stara Odpowiedź: Minęło trochę czasu od programowania winforms, ale jak pamiętam etykiety są domyślnie przezroczyste? tak więc jego tylko tekst, który dostaje rzeczywisty kolor a kolor imituje to co za nim jest:)

 0
Author: thmsn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-03-03 11:37:57

Jest możliwe, aby zrobić dokładnie to, co chcesz osiągnąć. To po prostu zajmuje trochę czasu, aby grać z kontroli. Można utworzyć kontrolkę etykiet z przezroczystym tłem i umieścić ją na pasku postępu.

Sprawdź moja odpowiedź na kolejne pytanie SO.

 0
Author: MaciekTalaska,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:26:04

Jeśli chodzi o wyjaśnienie problemu, windows nie robi przezroczystości dla kontrolek tła, jak można się spodziewać-domyślam się, że szare tło jest rzeczywiście powierzchnią formularza. wszystkie elementy sterujące rysowane między powierzchnią formularza a etykietą są ignorowane.

 0
Author: lincolnk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-10-05 17:42:00

Wybierz BackColor , Przejdź do zakładki Web i wybierz przezroczysty. Generuje następujące.

        this.label1.BackColor = System.Drawing.Color.Transparent;
 -3
Author: Steve,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-02-13 03:01:16