How to inherit events between objects

Go To StackoverFlow.com

0

I need inherit events and properties. For example, I need to move a picture around a form. I have this code to move one picture but I need to create multiple images with the same behavior.

private void pictureBox_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
         x = e.X;
         y = e.Y;
     }
 }

private void pictureBox_MouseMove(object sender, MouseEventArgs e)  
{
    if (e.Button == MouseButtons.Left)
    {
        pictureBox.Left += (e.X -x);
        pictureBox.Top += (e.Y - y);
    }
 }
2012-04-05 22:57
by marduck19


3

Create custom control:

public class MovablePictureBox : PictureBox
{
    private int x;
    private int y;

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

        if (e.Button == MouseButtons.Left)
        {
            x = e.X;
            y = e.Y;
        }
    }

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

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

UPDATE: Instead of attaching a delegates, you should override inherited event functionality, as Microsoft recommends here. After creating this control just compile program and drag your MovablePictureBoxes from Toolbox to form. They all will be draggable (or movable, if you wish).

2012-04-05 23:11
by Sergey Berezovskiy
thanks, but I have a problem when I want to implement the Custom Control you mention when I programmed the picturebox. How programmatically use this custom control for each picturebox in main class thank - marduck19 2012-04-07 18:48
@marduck19, if you want to create them programmatically, then just create exactly like standard picture boxes, but use class name MovablePictureBox instead. E.g. var pictureBox = new MovablePictureBox()Sergey Berezovskiy 2012-04-07 21:22
Thanks for helping friend and I understood very well. Greetings from Guadalajara Mexico = - marduck19 2012-04-08 00:21
@marduck19, glad I could help : - Sergey Berezovskiy 2012-04-08 07:38


1

What you really want to do is have your multiple PictureBoxes share the same event handlers:

private void pictureBox_MouseMove(object sender, MouseEventArgs e)   
{ 
    if (e.Button == MouseButtons.Left) 
    { 
        // the "sender" of this event will be the picture box who fired this event
        PictureBox thisBox = sender as PictureBox;            

        thisBox.Left += (e.X -x); 
        thisBox.Top += (e.Y - y); 
    } 
 }

Each PictureBox you create on your form keep hooking them up to the same, already created, event. If you look at the above code you'll notice that it determines which PictureBox called it and affects just that picture box.

2012-04-05 23:07
by Brad Rem
Ads