Visual C# (Windows) Guide
SFML Graphics: Dragging & Dropping
Dragging and dropping needs us to work with 3 mouse events
- MouseDown – working out which item is selected and beginning the drag/drop process.
- MouseMove – if an items is being dragged, moving it with the mouse pointer
- MouseUp – ending the drag/drop process.
We also need some additional fields in our Canvas class to help. These fields are,
private bool Dragging = false;
private int SelectedItem = 0;
The events are as follows,
protected override void OnMouseDown(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
for (int i = 0; i < Shapes.Count; i++)
{
if (Shapes[i].GetGlobalBounds().Contains(
new Vector2f((float)e.X, (float)e.Y)))
{
SelectedItem = i;
Dragging = true;
}
}
}
}
protected override void OnMouseMove(MouseEventArgs e)
{
if (Dragging)
{
float dx = Shapes[SelectedItem].GetGlobalBounds().Width/2;
float dy = Shapes[SelectedItem].GetGlobalBounds().Height/2;
Shapes[SelectedItem].Position = new Vector2f((float)e.X - dx,
(float)e.Y - dy);
this.Refresh();
}
}
protected override void OnMouseUp(MouseEventArgs e)
{
Dragging = false;
}
Test this with the 3 shapes from the earlier example code.
If the shapes are all CircleShape, then you can use the Radius property of the shape to work out the dx and dy offsets when doing the MouseMove. Something that you may want to do in an application is to work with a drop target. This would mean that your application did something when an item was dropped in a particular location. It is quite easy to extend the sample code here to do that. When you drop the item, check its position and see if it matches your drop target before triggering your code.

