Make a borderless form movable?

前端 未结 21 2160
情歌与酒
情歌与酒 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:18

    Best way I've found (modified of course)

    // This adds the event handler for the control
    private void AddDrag(Control Control) { Control.MouseDown += new System.Windows.Forms.MouseEventHandler(this.DragForm_MouseDown); }
    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();
    
    private void DragForm_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            ReleaseCapture();
            SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
            // Checks if Y = 0, if so maximize the form
            if (this.Location.Y == 0) { this.WindowState = FormWindowState.Maximized; }
        }
    }
    

    To apply drag to a control simply insert this after InitializeComponent()

    AddDrag(NameOfControl);
    

提交回复
热议问题