首页 > 解决方案 > 面板上的鼠标移动事件 - c# winform

问题描述

我有一个包含按钮的面板。我想在鼠标悬停时移动这个面板。我已经尝试过如下所示。但是当鼠标放在按钮上方时,面板不会移动。仅当鼠标在面板上时才有效。无论面板中的控件如何,我都必须使其在面板的任何点上工作。

        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;
        }
    }

标签: c#winformspanelonmousemove

解决方案


因为仅为面板添加事件处理程序,所以将相同的代码添加到按钮

Btn.MouseDown += panelLeft_MouseDown;

或者遍历面板内的每个控件并将事件处理程序分配给它们


推荐阅读