开发者

How to draw control border in efficent way

Hi I have my custom control on which I draw color border by overriding OnPaint method. However I would like to change the border color of my control if mouse enter the area of control and if mouse leave the control. At first I wanted to react on event mouseLeave and mouseEnter and repaint control border with a proper color. However in my control is several textboxes,labels etc - so events mouseEnter and mouseLeave fire quite a lot of times and this causes that my control blinks (because of many redraws).

Is there any bett开发者_运维知识库er way to find a proper moment to redraw control then react on mouseLeave and mouseEnter ??


You should invalidate your control only if the mouse is over it. You can check the position of the mouse by inspecting the static MousePosition variable, available for all controls. Just add a check to conditionally invalidate your control.

The simplest way to do this is to perform these checks from within the MouseEnter and MouseLeave events, then invalidate appropriately.

protected override void OnMouseEnter(EventArgs e)
{
    var mousePos = this.PointToClient(MousePosition);
    if (this.ClientRectangle.Contains(mousePos))
    {
        this.Invalidate(invalidateChildren: true);
    }
    base.OnMouseEnter(e);
}

protected override void OnMouseLeave(EventArgs e)
{
    var mousePos = this.PointToClient(MousePosition);
    if (!this.ClientRectangle.Contains(mousePos))
    {
        this.Invalidate(invalidateChildren: true);
    }
    base.OnMouseLeave(e);
}

For a more robust way to handle this, you need to determine whether or not the mouse actually enters or leaves your control. You would need to keep two variables to keep state, one to tell if the mouse is currently over your control and one to tell if the mouse was over your control (since the last time checked). If these are different, then invalidate your control. You'll get the added bonus of knowing whether the mouse is over your control so you can perform some operations in your paint method conditionally.

private bool wasMouseOver;
private bool isMouseOver;
public bool IsMouseOver { get { return isMouseOver; } }
private void CheckMousePosition()
{
    var mousePos = this.PointToClient(MousePosition);
    wasMouseOver = isMouseOver;
    isMouseOver = this.ClientRectangle.Contains(mousePos);
    if (isMouseOver != wasMouseOver)
        this.Invalidate(invalidateChildren: true);
}

// then register this method to the mouse events
EventHandler mouseHandler = (sender, e) => CheckMousePosition();
MouseEnter += mouseHandler;
MouseLeave += mouseHandler;
MouseMove += (sender, e) => CheckMousePosition();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜