Problem with OnPaint in custom label control

  • Thread starter Kenneth Siewers Møller
  • Start date


Kenneth Siewers Møller

Hi there

I have a custom label control (GradientLabel) which enherits from Label and
basically just paints the background of a label in a gradient.

In my code I have the following for the overidden OnResize event:

protected override void OnPaint(PaintEventArgs e)
Graphics g = e.Graphics;
using (LinearGradientBrush br = new LinearGradientBrush(e.ClipRectangle,
color1, color2, gradient_mode))
g.FillRectangle(br, e.ClipRectangle);

(The Color1 and Color2 and gradient_mode are set using properties to get the
designtime representation to work)

Now the odd part is this. I have two different machines, a desktop and a
laptop, both running .NET 2.0. On my desktop there is no problem when I
resize the control and the gradient follows nicely, also when I maximize the
window etc.
On my laptop however, everything works except when I maximize the form in
which the label resides. The gradient simply cuts off and starts over where
the form was maximized from.
I have tried overriding a lot of different events, including the forms own
OnResize event and then through that calling the labels Refresh() method,
but no luck.

What is the problem? I suspect it for being a machine specific problem, but
it would be nice if I somehow could get a reason :)

Another problem is when I drag another window across the label. It then
won't repaint itself. How do I get it to do that?

Kenneth, Denmark



Nicholas Paldino [.NET/C# MVP]


I think that your logic is wrong. Instead of passing the ClipRectangle,
what I would do is pass a rectangle which has the size of your label (from
0, 0 to length, width). The ClipRectangle is just the area of the screen
that needs repainting, not the whole label, so theoretically, your gradient
can shift depending on what needs to be refreshed.

Then, when you call FillRectangle, you can pass the clip rectangle and
the brush should be applied appropriately.

Hope this helps.

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question