Snap Moveable buttons to each other

Jimmythegreat

Member
Joined
Jul 19, 2006
Messages
17
Programming Experience
3-5
I have movable buttons on my form. To move them you right-click and drag them. I however cannot figure out the best way to "snap" them together. If anyone has any ideas on how to do this it would make me happy.

These buttons are created at runtime, if that makes a difference.

Thanks
Jimmy
 
My application has a similar facility.

I recommend rounding off the x and y positions to the nearest 8 pixels on your mouseup event.
 
I've started looking into something like this and have these ideas/suggestions:
  • Observe closely how the snapping works in VS IDE.
  • There are two types of snapping, what I call "inner" and "outer". Inner is when for example the selected control top snaps to another control top (or left to left, etc), ie like inside a "box". Outer where selected control left(+margin) snaps to another controls right(+margin) etc, ie opposite sides.
  • Work with the movement of the cursor, not the movement of the selected control. How the selected control moves is a consequence of the cursor movement. This is important for snap functionality, else you get a snap-lock where the control won't un-snap (when control is snapped it doesn't move any longer).
  • Define the direction the cursor moves (up,down,left,right). You only need to make two X or Y comparisons for each object in each direction.
  • See that VS IDE snapping works regardless of the different controls containers. The reason this is significant is because the control location is always relative to it's container. You need to understand the PointToClient and PointToScreen methods, always use screen points to compare different controls X/Y locations.
Attached is a sample project with one suggested implementation. Featuring a Snap class that can be used with any form/container, it expose only two methods Capture/Suspend for enabling runtime designer drag/snap functionality. IMessageFilter is used to catch low level mouse messages before they reach the form. It draw lines like VS to show what controls are aligned, but is in all "basic" :)
 

Attachments

  • vbnet20-SnapTo.zip
    15.5 KB · Views: 24
Last edited:
Back
Top