Julien Gidel Julien Gidel - 17 days ago 8
C# Question

Add MouseDown and MouseMove event on a class at runtime

I try to add an event handler to a personnal class that inherit from the .NET class "Panel".

I tried some several ways to do it but it's not working anymore...

I have a Principal Panel that contains other Panel. It's to design Grafcet.

So I have my class "Etape" that inherit from 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;
}
}
}


And I declare it like that :

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


"toto" is add to my "principal" Panel just after that.
I would like to add an Eventhandler to move my panels at runtime. I tried the code you can see above, but I think C# doesn't detect that I'm clicking on the Etape.

Do you have an idea or something to help me ?

Julien

Answer

You should override the OnMouseXXX methods:

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

Just declaring a method called Etape_MouseMove() doesn't hook anything up to it.