0

I have a rectangle with no background and I want to give it a translucent background when the user hovers their mouse over it, and then remove it when the mouse leaves the rectangle.

Is there any sample C# code that shows me how to do this?

I am basically doing an Windows Explorer style image viewer and looking for an identical method of highlighting the image that the mouse is currently hovering over.

Thanks.

Intrepid
  • 2,781
  • 2
  • 29
  • 54
  • 1
    You are highlighting it by make it translucent? Isn't that backwards? Otherwise nothing that a bool field and OnPaint() can't solve. Set it to true and call Invalidate() to force a repaint. – Hans Passant Jul 29 '13 at 11:51
  • Thanks Hans, before I give that a try, do I need to draw the highlight background first and then superimpose the image over that? – Intrepid Jul 29 '13 at 12:10
  • 2
    Your intended effect is hard to reverse-engineer from your question but that ought to be backwards too. Paint the image (or call base.OnPaint) and then draw whatever you want on top. Which is probably a rectangle filled with a brush that has an alpha of less than 255. You can also tinker with ColorMatrix when painting the image. – Hans Passant Jul 29 '13 at 12:16
  • Are you using a ListView control? Because if so, you can easily make it look the same as those used in Windows Explorer. – Cody Gray - on strike Jul 29 '13 at 12:29
  • @Cody: I cannot use a ListView control to do what I want to do. I have created a UserControl by drawing images of branded products directly using OnPaint() with two lines of text directly underneath each image to describe a title and the number of calories that product has. – Intrepid Jul 29 '13 at 13:31
  • @HansPassant: I have implemented your suggestion and it works great bar one annoying thing; the repaint is causing flickering. I have tried setting the DoubleBuffered property to True and this stops the flickering, but when the form is resized The form turns black for a fraction of a second before the OnPaint() kicks in. Is there any way to stop this happening as it's very ugly and unprofessional? – Intrepid Jul 29 '13 at 19:05
  • That's another question, [answered here](http://stackoverflow.com/a/3718648/17034). – Hans Passant Jul 29 '13 at 19:08
  • @HansPassant: just tried that and it still shows the black artefacts as the form maximises. I am using Windows 7 with Aero. – Intrepid Jul 29 '13 at 20:10
  • 1
    Of course I cannot guess at this from a comment, ask a proper question. – Hans Passant Jul 29 '13 at 20:13
  • Is the flickering black artefacts actually being caused by the default color of the double buffer? If so, is there any way of setting it to the same color as the form's background, i.e. setting it to White to see if that improves the appearance? – Intrepid Jul 29 '13 at 20:19
  • Use the [edit] link to update your question with sample code that reproduces the problem you describe. – Cody Gray - on strike Jul 30 '13 at 05:01

0 Answers0