Search code examples
c#winformsdrag-and-droptreeviewtreenode

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.


Solution

  • 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;