问题
I have an app where users can drag controls around on a Form. But they re asking me for Snap-To lines to make the alignment of controls easier. I have no idea about the snep-to lines and how to implement them - I have looked at:
http://msdn.microsoft.com/en-us/library/ms752100.aspx Adorner's, but it says it's only for WPF. And I tried it in WinForms but (as expected) didn't work.
How can I get snap-to lines (something like the ones in VS) in my app?
Thank you
Bael
回答1:
Have you seen this article on CodeProject:
Form Designer
It features snap-to to the grid on the design surface.
回答2:
In your move control you could adjust the Left
and Top
by dividing and then multiplying by the width of your lines:
left = (left/10)*10;
top = (top/10)*10;
It's not perfect but it it simple. Of course since controls don't have a MoveEnd event you'll have to track the MouseButton state or something similiar.
Edit: A better implementation would properly round the division results so 134 = 130 and 136 = 140.
回答3:
I had the same issue, I'm still looking for a solution ; here is what I did so far, it could be a solution for you
const grid = 12;
private void MyControl_LocationChanged(object sender, EventArgs e)
{
if (this.Left % grid != 0)
this.Left -= this.Left % grid;
if (this.Top % grid != 0)
this.Top -= this.Top % grid;
}
or in a usercontrol
protected override void OnMove(EventArgs e)
{
if (this.Left % grid != 0)
this.Left -= this.Left % grid;
if (this.Top % grid != 0)
this.Top -= this.Top % grid;
}
My current challenge is the drawing activity; my controls are hosted in a panel, I am looking for a way to lock and unlock that panel drawing when necessary; for example: only after left or top changed
来源:https://stackoverflow.com/questions/2211226/snap-to-lines-when-aligning-controls-at-runtime