Make a borderless form movable?

前端 未结 21 2018
情歌与酒
情歌与酒 2020-11-22 09:48

Is there a way to make a form that has no border (FormBorderStyle is set to \"none\") movable when the mouse is clicked down on the form just as if there was a border?

21条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 10:38

    Form1(): new Moveable(control1, control2, control3);

    Class:

    using System;
    using System.Windows.Forms;
    
    class Moveable
    {
        public const int WM_NCLBUTTONDOWN = 0xA1;
        public const int HT_CAPTION = 0x2;
        [System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
        [System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
        public static extern bool ReleaseCapture();
        public Moveable(params Control[] controls)
        {
            foreach (var ctrl in controls)
            {
                ctrl.MouseDown += (s, e) =>
                {
                    if (e.Button == MouseButtons.Left)
                    {
                        ReleaseCapture();
                        SendMessage(ctrl.FindForm().Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
                        // Checks if Y = 0, if so maximize the form
                        if (ctrl.FindForm().Location.Y == 0) { ctrl.FindForm().WindowState = FormWindowState.Maximized; }
                    }
                };
            }
        }
    }
    

提交回复
热议问题