如何在对象之间继承事件

时间:2012-04-05 22:57:53

标签: c# winforms inheritance picturebox

我需要继承事件和属性。例如,我需要在表单周围移动图片。 我有这个代码移动一张图片,但我需要创建具有相同行为的多个图像。

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

2 个答案:

答案 0 :(得分:3)

创建自定义控件:

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

更新: 您应该覆盖继承的事件功能,而不是附加委托,因为Microsoft建议使用here。 创建此控件后,只需编译程序并将MovablePictureBoxes从Toolbox拖动到form。它们都是可拖动的(如果你愿意,可以移动)。

答案 1 :(得分:1)

您真正想要做的是让多个PictureBox共享相同的事件处理程序:

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

您在表单上创建的每个PictureBox都会将它们挂钩到同一个已创建的事件中。如果您查看上面的代码,您会发现它确定哪个PictureBox调用它并影响该图片框。