MouseDown 시점에 Control.MousePosition 값과 MouseMove 시점 Control.MousePosition 값의 차이 만큼 폼을 이동 한다..
샘플은 폼 또는 Label 을 마우스로 이동하여 폼을 이동 한다.
Sample Form |
기능 구현.
public static class FormHelper { public static void SetMovingForm(this Form form, Control[] triggerControls, Cursor movingCursorOrNull = null) { bool mouseDown = false; Point lastMousePoint = new Point(); Cursor movingCursor; if (movingCursorOrNull == null) movingCursor = Cursors.NoMove2D; else movingCursor = movingCursorOrNull; Dictionary<Control, Cursor> oldCursors = new Dictionary<Control, Cursor>(); foreach (var item in triggerControls) { Control con = item; con.MouseDown += (s, e) => { var thisControl = s as Control; mouseDown = true; if (!oldCursors.ContainsKey(item)) oldCursors.Add(item, thisControl.Cursor); else oldCursors[item] = thisControl.Cursor; thisControl.Cursor = movingCursor; lastMousePoint = Control.MousePosition; }; con.MouseMove += (s, e) => { if (!mouseDown) return; Point currentPoint = Control.MousePosition; int x = currentPoint.X - lastMousePoint.X; int y = currentPoint.Y - lastMousePoint.Y; form.Location = new Point(form.Location.X + x, form.Location.Y + y); lastMousePoint = currentPoint; }; con.MouseUp += (s, e) => { var thisControl = s as Control; mouseDown = false; thisControl.Cursor = oldCursors[thisControl]; }; } } }
사용예.
public partial class Form1 : Form { public Form1() { InitializeComponent(); this.FormBorderStyle = FormBorderStyle.None; this.SetMovingForm(new Control[] { this, this.titleLabel }); } }
댓글 없음:
댓글 쓰기