Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mousewheel bubbling up in winforms?

I have a little problem with winforms and mousewheel events. I have a custom user control representing a slider. Now, I have a couple groups of sliders in which each group is wrapped inside a panel. All the groups are then wrapped in another panel (which has AutoScroll set to true) and this is wrapped in a form. The slider logic is implemented such that the mousewheel can be used to change its value. For this, the slider user control gets focus when the mouse is over the slider. However, when I scroll, also the AutoScroll parent panel scrolls with it. I've already lost a lot of time on this issue. Anybody knows what is happening here and how I can solve it? I thought the event was bubbling to the parent panel but I don't find a Handled property on the event when handling it in the Slider control (as is possible with WPF).

many thanks

like image 278
Chris Avatar asked Aug 08 '11 14:08

Chris


1 Answers

We implemented the Slider as a complete custom user control (inheriting the UserControl class) with own look-and-feel.

You might have noticed that a UserControl doesn't show the MouseWheel event in the Properties window. Hint of trouble there. The WM_MOUSEWHEEL message bubbles. If the control that has the focus doesn't handle it then Windows passes it on to its Parent. Repeatedly, until it finds a parent window that wants to handle it. The Panel in your case.

You'll need to invoke a bit of black magic in your slider control. The actual event args object that get passed to the MouseWheel event is not of the MouseEventArgs type as the event signature suggests, it is HandledMouseEventArgs. Which lets you stop the bubbling. Like this:

    protected override void OnMouseWheel(MouseEventArgs e) {
        base.OnMouseWheel(e);
        // do the slider scrolling
        //..
        ((HandledMouseEventArgs)e).Handled = true;
    }
like image 110
Hans Passant Avatar answered Oct 21 '22 15:10

Hans Passant