How to drag a shape in Windows Forms

I have a program written in C # / WindowsForms that draws circles (graph nodes) in a panel. I want to drag one circle to another place.

I have a dictionary that goes

Dictionary NodeMap<Node,Point>; 

So, from this event and MouseDown, I can find out which node I am dragging.

The problem is that it is not currently dragging a node, it just redraws it to a new position, so I have to click several times to move it.

My code for this part:

 private void pnlCanvas_MouseDown(object sender, MouseEventArgs e) { Node grabbedNode = new Node("-1"); Point loc = e.Location; loc.X = (int) (loc.X * 1000.0 / pnlCanvas.ClientSize.Width); loc.Y = (int) (loc.Y * 1000.0 / pnlCanvas.ClientSize.Height); foreach (var n in NodeMap) { if ((Math.Abs(n.Value.X - loc.X) < (sldNodeSize.Value)) && (Math.Abs(n.Value.Y - loc.Y) < (sldNodeSize.Value))) { grabbedNode = n.Key; break; } } if (grabbedNode.Id != "-1") { NodeMap.Remove(grabbedNode); NodeMap.Add(grabbedNode, loc); DrawGraph((short)sldNodeSize.Value); } } 
+4
source share
1 answer

As mentioned in a comment by John Arlen, I had to move the new location setting and repaint it in MouseMove, leaving MouseDown only for node detection. Then, using the global Node object and the variable variable isDraggingNode, I was able to achieve my goal. Thank you - rakoczyn

0
source

Source: https://habr.com/ru/post/1441601/


All Articles