views:

585

answers:

2

I'm working with a WPF app, more specifically a Canvas with draggable elements.

Once an item is being dragged, I'd like to limit the scope of cursor movement to inside the canvas where the items are being dragged about.

The event which can start a drag is shown below


private void WidgetCanvas_PreviewHeaderLeftMouseDown(object sender, MouseButtonEventArgs e)
{
     e.Handled = true;
     ... logic to figure out if this is a valid drag, blah blah blah ...

     this.IsDragging = true;
     // TODO: clip the available cursor movement to actual width of Canvas
}

On the Preview-MouseUp, I'd like to simply "unclip" the cursor movement back to it's normal state.

I'll be monitoring the movement of the mouse once I start dragging (PreviewMouseMove), so worst case, I could manually check the position of the mouse and keep it constrained to the canvas, but that seems a little ugly.

Anyone have a better way to limit the cursor boundaries?

+2  A: 

There's no clean way to do this and the not-so-clean ways will make your mouse cursor "jitter" at the border of the clipping area.

Moreover, I'd question if this is really a good idea. The user should really own the mouse and he or she generally gets frustrated when you try to artificially limit things that he or she owns.

If you want to provide feedback when the mouse leaves your canvas, maybe you could leave the item being dragged stuck along the border while the mouse button is still down? This would tell the user that he or she has left the target area without trying to impose limitations on where the mouse can go.

Good luck!

Naaff
After reading your comments, and few more on MSDN that echoed the same sentiment, I ended up doing just this. I monitor the items for an event which will start the dragging (as dragging only starts when the use mouse downs on the header of the items). Once dragging starts, I capture the mouse on the canvas, and allow the item to be dragged to the end of the canvas but no further. Positioning of the items can change even if the mouse is not on the canvas, as long as the there is no MouseUp.
corey broderick
This sounds like a good solution. Thanks for posting an update... it's nice to see what worked out for you.
Naaff
A: 

You should be able to do it using the ClipCursor native API.

Thomas Levesque