While implementing drag and drop operation, it might be necessary to change the drag cursor. There could be several reasons for doing so. For example, you might want to have different cursors for different categories of nodes dragged from a tree. Similarly, you might want different cursors in the different regions of the same target component.

The most important thing that should be understood while doing so is that, it is always the source component/control that is responsible for changing the drag cursor. Many programmers do not know this fact, and try to write the cursor changing code based on the drop target control. However, for the source to change the cursor, it needs some instructions/conditions which the target control can provide. Of course, in the absence of explicit instruction from target, there is always a default provision that governs the cursor.

In other words, suppose a node is being dragged from a tree to a panel. And, we want to different cursors for different regions within the panel. In this case, we check the mouse over coordinates and based on this, instruct the source tree to change the drag cursor.

For this, we need to handle ‘GiveFeedback’ event for the source control. As per above supposition, this source control is a tree. Then, we might have something like below.

myTree.GiveFeedback += MyTree_GiveFeedback;

Next, we write the code for changing the default drag cursor inside the handler for this event. The condition for changing cursor is derived from DragDropEffects type parameter. An example is shown below.

void MyTree_GiveFeedback(object sender, GiveFeedbackEventArgs e)
{
if (e.Effect == DragDropEffects.Move)
{
e.UseDefaultCursors = false;
Cursor.Current = Cursors.Hand;
}
else if (e.Effect == DragDropEffects.Copy)
{
e.UseDefaultCursors = false;
Cursor.Current = Cursors.Cross;
}
else if (e.Effect == DragDropEffects.None)
{
e.UseDefaultCursors = false;
Cursor.Current = Cursors.No;
}
else
{
e.UseDefaultCursors = true;
}
}

Now, at the target side, we add a handler for the event ‘DragOver’, i.e. something like below.

myPanel.DragOver += MyPanel_DragOver;

And inside the handler, we put the logic to change the value of DragDropEffects parameter.

void MyPanel_DragOver(object sender, DragEventArgs e)
{
if ( condition1() )
{
e.Effect = DragDropEffects.Move;
return;
}
if ( condition2() )
{
e.Effect = DragDropEffects.Copy;
return;
}
if ( condition3() )
{
e.Effect = DragDropEffects.None;
return;
}

e.Effect = DragDropEffects.All;
}

And thats it. With the conjuction of logic in target’s DragOver event handler and source’s GiveFeedback event handler, it is very easy to change the drag cursor based upon the conditions in the target control.



No Responses Yet to “Changing the drag cursor in C#”  

  1. No Comments Yet

Leave a Reply