Move the mouse to a component [solved]


#1

Is it possible to move the mouse (cursor) programatically to a component? Say I have a component e.g. a cursor that moves “by itself” due to automation. When I click on it (or its containing component), I want the mouse to snap to its position so I can continue record the automation from that moment smoothly without any discontinuity. I.e, the opposite behaviour the juce slider exhibits, where the the thumb snaps to the mouse.


#2

There is MouseInputSopurce::setScreenPosition (Point< float > newPosition).
To get the MouseInputSource, you can ask the Desktop: Desktop::getMouseSource (int index) const.

I don’t know, how straight forward it is, because systems can have more than one MouseInputSources. But you can query them all. It is just up to you, which one to move in doubt. For the standard case, using the first MouseInputSource probably is a good start.

HTH


#3

Thanks, works halfway.

The following code positions the mouse right on myCursor when its parent is clicked. But I can’t drag it as I can if I click directly on it because it doesn’t receive any mouseDown event. So what is needed now is a way to transfer a mouse down event from one component to another, which seems to be far from trival…

void MyComponent::mouseDown(const MouseEvent& e) noexcept
{
    e.source.setScreenPosition(myCursor->getScreenBounds().getCentre().toFloat());
}

#4

You can always hide the cursor when the dragging event happens, and just make any math relative to the distance from the starting position, then reset the mouse position on a mouseUp event.

If you want one component to share mouse events with another you just need to register the second component as a mouseListener using Component::addMouseListener


#5

Thanks Holy_City. It turned out to be easier than I feared to transfer the drag from the parent component to the sliderThumb.

Here’s the complete solution to move the mouse to the current position of the slider thumb (or whatever appropriate child component) and smoothly continue the drag from its current position (instead of the usual thumb jump to the mouse position)

void MyComponent::mouseDown(const MouseEvent& e) noexcept
{
    e.source.setScreenPosition(mySliderThumb->getScreenBounds().getCentre().toFloat());

    MouseEvent eThumb = e.withNewMouseDownPosition(mySliderThumb->getBounds().getCentre());
    mySliderThumb->sliderThumbDragger.startDraggingComponent(mySliderThumb, eThumb);
}

and in

void MyComponent::mouseDrag(const MouseEvent& e) noexcept
{
    mySliderThumb->sliderThumbDragger.dragComponent(mySliderThumb, e, nullptr);
}

Hmm, well not quite, the mouse cursor isn’t changed to a dragging cursor but stays in its normal arrow mode during the drag, but I gues I can live with that…


#6

You can call Component::setMouseCursor (MouseCursor::DraggingHandCursor) in your mouse event callback.


#7

Thanks man, looks really neat now…