在运行时在 class 上添加 MouseDown 和 MouseMove 事件

Add MouseDown and MouseMove event on a class at runtime

我尝试向从 .NET class "Panel".

继承的个人 class 添加事件处理程序

我尝试了几种方法,但它不再起作用了...

我有一个包含其他面板的主面板。是为了设计Grafcet

所以我的 class "Etape" 继承自 Panel :

 class Etape : Panel
    {
        private Point MouseDownLocation;

        private void Etape_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                MouseDownLocation = e.Location;
                this.BackColor = CouleurSelect;
                MessageBox.Show("Bonjour");
            }
        }

        private void Etape_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.Left = e.X + this.Left - MouseDownLocation.X;
                this.Top = e.Y + this.Top - MouseDownLocation.Y;
            }
        }
    }

我是这样声明的:

 toto = new Etape();
 toto.BackColor = Color.White;
 toto.BorderStyle = BorderStyle.FixedSingle;
 toto.Width = 40;
 toto.Height = 40;
紧接着

"toto" 添加到我的 "principal" 面板。 我想添加一个事件处理程序来在运行时移动我的面板。我尝试了您在上面看到的代码,但我认为 C# 没有检测到我正在单击 Etape。

你有什么想法或什么可以帮助我吗?

朱利安

您应该覆盖 OnMouseXXX 方法:

class Etape : Panel
{
    private Point MouseDownLocation;

    protected override void OnMouseDown(MouseEventArgs e)
    {
        base.OnMouseDown(e);

        if (e.Button == MouseButtons.Left)
        {
            MouseDownLocation = e.Location;
            this.BackColor = CouleurSelect;
            MessageBox.Show("Bonjour");
        }
    }

    protected override void OnMouseMove(MouseEventArgs e)
    {
        base.OnMouseMove(e);

        if (e.Button == MouseButtons.Left)
        {
            this.Left = e.X + this.Left - MouseDownLocation.X;
            this.Top = e.Y + this.Top - MouseDownLocation.Y;
        }
    }
}

只是声明一个名为 Etape_MouseMove() 的方法并没有关联任何东西。

您需要将函数挂接到事件

class Etape : Panel
    {
        public Etape()
        {
            MouseDown += Etape_MouseDown;
            MouseMove += Etape_MouseMove;
        }

        private Point MouseDownLocation;

        private void Etape_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                MouseDownLocation = e.Location;
                this.BackColor = CouleurSelect;
                MessageBox.Show("Bonjour");
            }
        }

        private void Etape_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.Left = e.X + this.Left - MouseDownLocation.X;
                this.Top = e.Y + this.Top - MouseDownLocation.Y;
            }
        }
    }