Make a borderless form movable?

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

    I tried the following and presto changeo, my transparent window was no longer frozen in place but could be moved!! (throw away all those other complex solutions above...)

       private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            base.OnMouseLeftButtonDown(e);
            // Begin dragging the window
            this.DragMove();
        }
    
    0 讨论(0)
  • 2020-11-22 10:38

    use MouseDown, MouseMove and MouseUp. You can set a variable flag for that. I have a sample, but I think you need to revise.

    I am coding the mouse action to a panel. Once you click the panel, your form will move with it.

    //Global variables;
    private bool _dragging = false;
    private Point _offset;
    private Point _start_point=new Point(0,0);
    
    
    private void panel1_MouseDown(object sender, MouseEventArgs e)
    {
       _dragging = true;  // _dragging is your variable flag
       _start_point = new Point(e.X, e.Y);
    }
    
    private void panel1_MouseUp(object sender, MouseEventArgs e)
    {
       _dragging = false; 
    }
    
    private void panel1_MouseMove(object sender, MouseEventArgs e)
    {
      if(_dragging)
      {
         Point p = PointToScreen(e.Location);
         Location = new Point(p.X - this._start_point.X,p.Y - this._start_point.Y);     
      }
    }
    
    0 讨论(0)
  • 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; }
                    }
                };
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题