Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Hot Track" effect on a Windows Form UserControl

What is the easiest way to implement a UserControl that mimics a "hot track" effect of drawing a border around itself when a mouse is hovering above it?

I have unsuccessfully tried to inherit a custom control that overrides the OnMouseHover event that draws the border (it seems as if the event is not being fired)

Thanks!

like image 480
Gerard Avatar asked Nov 04 '22 22:11

Gerard


1 Answers

You can simulate the appearance of a border around your User Control by using a carefully placed Panel control in your UC and watching for the position of the mouse by monitoring low level Windows messages.

On the UserControl design surface add a Panel and size the Panel so that only a small part of UC's design surface is visible (see note* below). The visible portion of the design surface is going to be your colored border so set its 'thickness' accordingly. Add the other controls that compose your UC to the panel.

Your control might look like this:
enter image description here

Implement the IMessageFilter interface in your UC. In your implementation of PreFilterMessage() you'll check for the position of the mouse relative to the UC and set the UC's BackColor to your border color when the mouse is over the UC, or back to a default color when it is not. Because the BackColor of the Panel doesn't change it will appear to the user like your UC ahs a border.

Here's the minimum amount of code you'll need to do this:

public partial class UserControl1 : UserControl, IMessageFilter
{
    public UserControl1() {
        InitializeComponent();
        Application.AddMessageFilter(this);
    }

    public bool PreFilterMessage(ref Message m) {
        if (!this.IsDisposed && this.ClientRectangle.Contains(this.PointToClient(Control.MousePosition))) {
            this.BackColor = Color.Green; // Or whatever border color you want.
        } else {
            this.BackColor = SystemColors.Control;  // Back to the UC's default border color.
        }
        return false;
   }
}

Note: When I tested this I had difficulty getting my Panel's BackColor setting to not be transparent. I fixed this by temporarily changing the BackColor in the designer to a different color and then changing it back to my default color (Control).

like image 99
Jay Riggs Avatar answered Nov 12 '22 13:11

Jay Riggs