I have been working on a custom container control. I wanted the parent autoscroll inherited control to scroll with the mouse wheel, but when a contained control had focused, this wouldn't happen because the child control received the mouse events.
Many people use Windows APIs for this, to tell the window to scroll, but I found that tedious and the results weren't always preferable. After thinking about it, I realized that you could just call the container controls
onMouseWheel
base class method directly, and pass to it the mouse event args from the child control.
public void doMouseWheel(MouseEventArgs e)
{
base.OnMouseWheel(e);
}
Simply creating a
public
method that handles calling the base class to our container control and for simplicity giving it an interface that shows it has this method:
public interface IMouseable
{
void doMouseWheel(MouseEventArgs e);
}
Then in our child control, we just override its
onMouseWheel
event and call our parent
IMouseable
object's
doMouseWheel
method.
protected override void OnMouseWheel(MouseEventArgs e)
{
base.OnMouseWheel(e);
((IMouseable)(Parent)).doMouseWheel(e);
}
Yes, I do realize that is a messy cast, but this code is for educational purposes only.
And it's that simple, No API calls, no fancy event handling (although you could technically just subscribe to the child contols'
onMouseWheel
event and call the base class method that way, but this example doesn't show the reasons why it is simpler to use the interface. In my production code, there is actually a ladder of controls below the container control, and all of them could have focus and should taxi the scroll event upward to the parent.
It's not the only way, it might not be the best way, But I am very satisfied with the results of it so far.