开发者

"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 arou开发者_JS百科nd 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!


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:

"Hot Track" effect on a Windows Form UserControl

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).


Try adding handlers to the control's "MouseEnter" and "MouseLeave" events that will change the control's BorderStyle (if it has one). MouseEnter is fired when the mouse moves inside the border of the control, and MouseLeave is fired when the mouse exits that border. MouseHover may have some additional rules, like the mouse has to be stationary for a certain time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜