Search code examples
c#winformspanelonmousemove

Mouse move event on panel - c# winform


I have a panel which contains a button. I want to move this panel on mouse over. I ahve tried like below. But when mouse put above the button, the panel is not moving. Only working when mouse is on the panel. I have to make it work on any point of panel irrespective of controls in it.

        this.panelLeft.Controls.Add(this.button1);
        this.panelLeft.Location = new System.Drawing.Point(21, 171);
        this.panelLeft.Name = "panelLeft";
        this.panelLeft.Size = new System.Drawing.Size(662, 324);
        this.panelLeft.TabIndex = 15;
        this.panelLeft.MouseDown += new System.Windows.Forms.MouseEventHandler(this.panelLeft_MouseDown);
        this.panelLeft.MouseMove += new System.Windows.Forms.MouseEventHandler(this.panelLeft_MouseMove);

   private void panelLeft_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            MouseDownLocation = e.Location;
        }
    }
    private void panelLeft_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            panelLeft.Left = e.X + panelLeft.Left - MouseDownLocation.X;
            panelLeft.Top = e.Y + panelLeft.Top - MouseDownLocation.Y;
        }
    }

Solution

  • Because the event handler is only added for panel add the same code to the button

    Btn.MouseDown += panelLeft_MouseDown;
    

    Or loop over each control inside panel and assign the event handler to them