Question

c#: transparent label control

Asked by: BlearyEye

I'm using vs2008 on vista. .Net's standard controls do not support transparency, so custom controls are necessary. At http://www.doogal.co.uk/transparent.php, I found the control given below.

When I assign or change the value in the text property for the control, it does no show up on the design window; but after I run the program, it shows up. Similarly, when I change the value in the program, it does not show up.

So, something's missing from the control ... ideas?

public class TransparentLabel : Control {
        /// <summary>
        /// Creates a new <see cref="TransparentLabel"/> instance.
        /// </summary>
        public TransparentLabel() {
            TabStop = false;
        }
 
        /// <summary>
        /// Gets the creation parameters.
        /// </summary>
        protected override CreateParams CreateParams {
            get {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x20;
                return cp;
            }
        }
 
        /// <summary>
        /// Paints the background.
        /// </summary>
        /// <param name="e">E.</param>
        protected override void OnPaintBackground(PaintEventArgs e) {
            // do nothing
        }
 
        /// <summary>
        /// Paints the control.
        /// </summary>
        /// <param name="e">E.</param>
        protected override void OnPaint(PaintEventArgs e) {
            using (SolidBrush brush = new SolidBrush(ForeColor)) {
                e.Graphics.DrawString(Text, Font, brush, -1, 0);
            }
        }
    }

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-07-29 at 08:06:49ID24609795
Topics

.NET

,

C# Programming Language

,

Microsoft Visual C#.Net

Participating Experts
4
Points
500
Comments
22

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Transparent Frame ?
    How to make a transparent frame? An API call answer is preferred. Thanks. Henry henrychan@poboxes.com
  2. transparent text
    I want a control that 1) can show text on a form 2) have transparent background, so video, pictures or labels can be seen through the text 3) one or more words can have different color, which can chahge dynamically (e.g. using Seltext, Selcolor) 4) enable selecting a word...
  3. Transparency
    I want to create an image that is transparent around the outside (select transparent background 'on create'), and also when I draw a square on this image, the square also has 50% opacity. The result is a totally transparent bitmap with a patch of color of the square. But I co...
  4. Transparent PictureBox / ListView
    Hello, What should I do in order to make my PictureBox / ListView Transparent ? thanks.
  5. Label transparency
    In my programm I'm putting a lot of labels on a picturebox dynamically, in some of the cases these labels overlap each other but I still want to see the underlying text, I tried to make the backcolor transparent but that doesn't work. Does anybody know a solution for this pro...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: ToddBeaulieuPosted on 2009-07-29 at 08:38:45ID: 24971309

Hard to say, without working with that library, but drawing text like that on the design form is the responsibility fo the custom control, so it sure sounds like a bug in the library to me.

 

by: mac-willPosted on 2009-07-29 at 09:34:57ID: 24971942

After you change the text value you would need to invalidate the control to force a re-paint.

A better approach might be to use something like this:

public class TransparentLabel : Label {
        /// <summary>
        /// Creates a new <see cref="TransparentLabel"/> instance.
        /// </summary>
        public TransparentLabel() {
        }
 
        /// <summary>
        /// Gets the creation parameters.
        /// </summary>
        protected override CreateParams CreateParams {
            get {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x20;
                return cp;
            }
        }
 
        /// <summary>
        /// Paints the background.
        /// </summary>
        /// <param name="e">E.</param>
        protected override void OnPaintBackground(PaintEventArgs e) {
            // do nothing
        }
 
    }

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:

Select allOpen in new window

 

by: BlearyEyePosted on 2009-07-29 at 10:25:03ID: 24972430

mac-will: it looks like you just removed the constructor and the OnPaint method. When I commented those out, nothing happens.

 

by: FernandoSotoPosted on 2009-07-29 at 10:36:51ID: 24972541

Hi BlearyEye;

To your question, "When I assign or change the value in the text property for the control, it does no show up on the design window", this may happen if the label is on top of another control and its z-order is not set to be the first. You can select the label control and right click on it. Then from the context menu select "Bring to Front".

To your question, "Similarly, when I change the value in the program, it does not show up", This may also be happening for the above reason but also that the system has not yet updated the UI. The simplest way to solve this issue is when you change the Text property of the label do it in a function as shown in the snippet this way you can force an update.

        private void ChangeLableText(string changeTo)
        {
            transparentLabel1.Text = changeTo;
            this.Invalidate(true);
        }

Fernando

 

by: ToddBeaulieuPosted on 2009-07-29 at 10:41:34ID: 24972593

I suspect the problem is at design time, when the property value is set via the properties editor. An invalidate would probably need to put in the property setter.

 

by: GuitarRichPosted on 2009-07-29 at 10:42:45ID: 24972602

This doesn't directly answer the question - but I'm using VS2008 on Vista and I can quite succesfully set the background color of a label to Transparent and its working fine for me. When you say transparency is not supported - what do you mean? All the controls I've needed to have with a transparent background so far have worked fine.

 

by: ToddBeaulieuPosted on 2009-07-29 at 10:44:02ID: 24972614

You know ... that was my first impression. I quickly dismissed it, thinking I was being dumb. Was too lazy to test it. :)

 

by: mac-willPosted on 2009-07-29 at 10:48:58ID: 24972663

No, I also change the parent class!!!

public class TransparentLabel : Label

NOT

public class TransparentLabel : Control

 

by: ToddBeaulieuPosted on 2009-07-29 at 10:51:56ID: 24972687

Which probably aquires the built-in "invalidation" when the Text property is set, regardless of how it's set, right?

 

by: BlearyEyePosted on 2009-07-29 at 11:06:33ID: 24972843

mc-will: sorry, I missed that.

OK, I made the change and am closer since it now updates the text. However, there are some new issues.

1. The background that gets painted dynamically is wrong. There are several graphics on the form and it looks like the background chosen is part of another graphic that's a fair distance away from the label.

2. The previous text in the label is still there; it doesn't get erased when the new text is added.

3. In the designer, and until the first assignment in the program, the label shows up with a white background.

 

by: mac-willPosted on 2009-07-30 at 05:37:40ID: 24979002

These are re-painting issues.  Because the label is not painting it's background you need to have what ever is behind it invalidate the label retangle so that it repaints the background you want.

You could maybe do something cleaver in the OnPaintBackground override like:

this.Parent.Invalidate(this.myRectangle)

 

by: mac-willPosted on 2009-07-30 at 05:42:01ID: 24979051

Todd:  Yes I believe the Label control would have all the invalidation built in.

 

by: BlearyEyePosted on 2009-07-30 at 06:45:24ID: 24979715

hmmm ... invaidating the parent means that the transparentlabel control will be called continuously (invaliate -> call transparentlabel -> invalidate). I guess I'll ned to add a switch..

 

by: mac-willPosted on 2009-07-30 at 08:16:36ID: 24980663

Add this to the class and it should do it for you.

protected void InvalidateEx()
         {
  
            if (Parent == null)
                 return;
 
            Rectangle rc = new Rectangle(this.Location, this.Size);
 
            Parent.Invalidate(rc, true);
         }
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:

Select allOpen in new window

 

by: FernandoSotoPosted on 2009-07-30 at 09:09:19ID: 24981279

Hi BlearyEye;

Try this, leave your TransparentLabel class as originally posted that inherits from Control.  When you add the TransparentLabel control to the form add its TextChanged event handler. Then in the event handler do the invalidate, like so:

        private void transparentLabel1_TextChanged(object sender, EventArgs e)
        {
            this.Invalidate(true);
        }

Fernando

 

by: BlearyEyePosted on 2009-08-11 at 08:29:03ID: 25070176

(sorry for the delay ... been travelling)

mac-will:

I added the method but it seems to have no effect. See complete class below.

public class TransparentLabel : Label {
        public TransparentLabel() {
        }
        protected override CreateParams CreateParams {
            get {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x20;
                return cp;
            }
        }
        protected override void OnPaintBackground(PaintEventArgs e) {
            // do nothing
        }
 
        // added by suggestion of mac-will
        protected void InvalidateEx() {
 
            if (Parent == null)
                return;
 
            Rectangle rc = new Rectangle(this.Location, this.Size);
 
            Parent.Invalidate(rc, true);
        }
    }
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:

Select allOpen in new window

 

by: BlearyEyePosted on 2009-08-11 at 08:39:02ID: 25070288

FernandoSoto:

The control is called ClipLength. I added the following to the form code as you suggested

        private void ClipLength_TextChanged(object sender, EventArgs e) {
            this.Invalidate(true);
        }

I used the control as originally posted. This seemed to have no effect. I put a breakpoint on the code and it appears that the TextChanged method is never called. I'm changing the text from program code, not from user interaction.

 

by: mac-willPosted on 2009-08-13 at 08:58:07ID: 25089868

ya, it doesn't seem to work with the label control.
You can try this class and see if it does the trick for you:

class TransparentLabel : Control
    {
 
        public TransparentLabel(Control parent)
         {
             this.Parent = parent;
         }
 
        protected void InvalidateEx()
        {
 
            if (Parent == null)
                return;
 
            Rectangle rc = new Rectangle(this.Location, this.Size);
 
            Parent.Invalidate(rc, true);
        }
 
         protected override CreateParams CreateParams
         {
             get
             {
                 CreateParams cp = base.CreateParams;
                 cp.ExStyle |= 0x0000020;
                 return cp;
             }
         }
 
         protected override void OnPaintBackground(PaintEventArgs e)
         {
             // do nothing
         }
 
         protected override void OnPaint(PaintEventArgs e)
         {
             using (SolidBrush brush = new SolidBrush(base.ForeColor))
             {
                 e.Graphics.DrawString(base.Text, base.Font, brush, -1, 0);
             }
         }
 
 
    }

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:

Select allOpen in new window

 

by: BlearyEyePosted on 2009-08-18 at 13:11:56ID: 25127120

I see what you did: changed the constructor to make the parent explicit.

It seems to be working now (yay), but I had to add the following:

   To InitializeComponent:
        this.ClipLength.TextChanged += new System.EventHandler(ClipLength_TextChanged);

    To the form class:
        private void ClipLength_TextChanged(object sender, EventArgs e) {
            this.Invalidate(true);
        }

Otherwise, nothing happened.

I tried using this.ClipLength.Invalidate(true), but it did not erase the current contents of ClipLength; new text overwrote the old stuff. Apparently I'm invalidating the entire form, which seems inefficient.

The TransparentLabel control code includes a method InvalidateEx(). I added a breakpoint to the method and apparently it's never being called. I changed it to the attached snippet, but when I use this.ClipLength.Invalidate(true), the overwriting still happens.

        protected new void Invalidate()
        {
 
            if (Parent == null)
                return;
 
            Rectangle rc = new Rectangle(this.Location, this.Size);
 
            Parent.Invalidate(rc, true);
        }
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:

Select allOpen in new window

 

by: mac-willPosted on 2009-08-20 at 05:37:33ID: 25141634

try this as you shouldn't need to override the entire form.

public override String Text
{
get
{
   return base.Text;
}
 
set
{
   if(value != base.Text)
   {
      base.Text = value;
      this.InvalidateEx();
   }
}
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:

Select allOpen in new window

 

by: BlearyEyePosted on 2009-08-23 at 03:33:17ID: 25162080

This last version seems to work. The key points are:
- specify the control explicitly
- clear the background part when text changed

below is a somewhat cleaned-up version of the control.

    public class TransparentLabel : Control {
        //
        // Constructor specifies parent control. 
        // This is what will be refreshed when label text is changed
        //
        public TransparentLabel(Control parent) {
            this.Parent = parent;
        }
        //
        // When text value changes, invalidate corresponding area of parent
        //
        public override String Text {
            get {
                return base.Text;
            }
            set {
                if (value != base.Text) {
                    base.Text = value;
                    if (this.Parent == null)
                        return;
                    Rectangle rc = new Rectangle(this.Location, this.Size);
                    this.Parent.Invalidate(rc, true);
                    this.Parent.Update();
                }
            }
        }
        protected override CreateParams CreateParams {
            get {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x0000020;
                return cp;
            }
        }
        protected override void OnPaintBackground(PaintEventArgs e) {
            // do nothing
        }
        protected override void OnPaint(PaintEventArgs e) {
            using (SolidBrush brush = new SolidBrush(base.ForeColor)) {
                e.Graphics.DrawString(base.Text, base.Font, brush, -1, 0);
            }
        }
    }
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:

Select allOpen in new window

 

by: BlearyEyePosted on 2009-08-23 at 03:35:32ID: 31609272

See final post by blearyeye for complete version of the control.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...