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

时间:2016-11-23 13:40:34

标签: c# runtime eventhandler

我尝试将一个事件处理程序添加到继承自.NET类" Panel"的人员类中。

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

我有一个包含其他Panel的主要小组。它是设计Grafcet的。

所以我有我的班级" 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"是我的"校长"小组就在那之后。 我想添加一个Eventhandler来在运行时移动我的面板。我尝试了上面可以看到的代码,但我认为C#没有检测到我点击了Etape。

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

于连

2 个答案:

答案 0 :(得分:2)

您应该覆盖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()的方法并不会将任何内容挂钩。

答案 1 :(得分:0)

您需要将函数挂钩到事件

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