MouseLeave not fired C# WinForms

2019-07-20 19:38发布

I have a user control with 2 buttons, that should only be visible when the mouse is inside the area of the control.

I'm showing the buttons like this:

private void Node_MouseEnter(object sender, EventArgs e){           
    btn1.Show();
    btn2.Show();
}

And hiding like this:

protected override void OnMouseLeave(EventArgs e){
    if (this.ClientRectangle.Contains(this.PointToClient(Control.MousePosition)))
        return;
    else
        base.OnMouseLeave(e);
}

private void Node_MouseLeave(object sender, EventArgs e){  
    btn1.Hide();
    btn2.Hide();
}

The problem is that sometimes (random situations) the MouseLeave event is not fired, and the buttons stay visible, even with the mouse outside the control.

Is it possible that multiple events get in conflict ?

1条回答
手持菜刀,她持情操
2楼-- · 2019-07-20 20:21

As this link states:

Mouse move messages are not accurate enough, they don't guarantee that every traversed pixel is reported. When you have a child window close to the edge of its parent, it is quite easy to not get the MouseEnter for the parent when you move the mouse fast enough.

So, the solution was to listen only for the MouseEnterevent, and when this event is fired, i send a notification to the other controls, to hide its buttons.

Is not the most elegant solution, but it works as expected.

查看更多
登录 后发表回答