Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent drag and drop outside of the current control (TreeNodes in a TreeView)

I'm maintaining a Windows app that has multiple forms in the one window (form1, form2, form3). I'm treating the other form2 and form3 as black boxes at the moment. In form1 I have a TreeView, and I'm implementing drag and drop functionality within that TreeView.
How can I prevent a drop outside of the form1 control?

I'm implementing 3 events handlers:

private void treeView_ItemDrag (...)
{
    DoDragDrop(e.Item, DragDropEffects.Move);
} 

private void treeView_DragEvent (...) 
{
    e.Effect = DragDropEffects.Move;
}

private void treeView_DragDrop (...)
{
    //the node move logic here
}

form2 and form3 have a drag and drop relationship between them, so when I drag a node from form1 into form3 by default it allows the move (bad). I want to be able to prevent this from the form1 control code.

How can I prevent a drop outside of the form1 control? I've looked at the _DragLeave event, but I'm unsure how to control the operation without the DragEventArgs.

like image 873
MattyG Avatar asked Jan 18 '23 02:01

MattyG


2 Answers

There is this little know property in the Cursor object that can restrict the mouse movement only to a certain rectangle.

this as a global variable for Form1

   Rectangle _originalClip;

this goes in your Form1_Load event

  _originalClip = Cursor.Clip;

this could be in your treeView.ItemDrag, forcing the cursor inside the form1 client area

   Cursor.Clip = form1.RectangleToScreen(form1.ClientRectangle);

Now you need to restore the original clip area. A good place will be in the treeView.DragDrop. But to be on the safe side put also in your Form1_Closing event

   Cursor.Clip = _originalClip;
like image 156
Steve Avatar answered Jan 24 '23 15:01

Steve


You can check if mouse drag action is going outside the allowed area, and if so, cancel the drag action.

There's a nice sample in MSDN that uses the QueryContinueDrag event for that purpose. I think you can use that on the base of your solution.

Link: DragAction Enumeration

like image 33
jjokela Avatar answered Jan 24 '23 16:01

jjokela