Form tool class (1) irregular form movement

In the development, there are some commonly used methods. It is troublesome to find the previously written ones every time. If you write them yourself, you are doing repetitive work, so there is always a small tool class and you can add content at any time.

1. Irregular form moving static class FormTools (public static class FormTools)

Method 1: Press the mouse and drag on the form

        /// <summary>
        /// Irregular form movement
        /// </summary>
        /// <param name="form">Form object to move</param>
        public static void MoveForm(this Form form)
        {
            var moveOffset = new Point();
            form.MouseMove += (sender, e) =>
            {
                if (e.Button != MouseButtons.Left) return;
                var mousePos = Control.MousePosition;
                mousePos.Offset(moveOffset.X, moveOffset.Y);
                form.Location = mousePos;
            };
            form.MouseDown += (sender, e) => { moveOffset = new Point(-e.X, -e.Y); };
        }

Method 2: Press the mouse on the control of the form and drag the form

        /// <summary>
        /// Irregular form movement
        /// </summary>
        /// <param name="control">Trigger control</param>
        /// <param name="form">Form object to move</param>
        public static void MoveForm(this Form form,Control control)
        {
            var moveOffset = new Point();
            control.MouseMove += (sender, e) =>
            {
                if (e.Button != MouseButtons.Left) return;
                var mousePos = Control.MousePosition;
                mousePos.Offset(moveOffset.X, moveOffset.Y);
                form.Location = mousePos;
            };
            control.MouseDown += (sender, e) => { moveOffset = new Point(-e.X, -e.Y); };
        }

transfer

Method 1 calls:

this.MoveForm();

Method 2 calls:

this.MoveForm(panel2);
Note: this is the current form object, which means that these two methods should be called in the winform form.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325627611&siteId=291194637