0

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

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

2 回答 2

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在此处建议的那样。创建此控件后,只需编译程序并将您的 MovablePictureBoxes 从 Toolbox 拖到窗体中。它们都是可拖动的(或可移动的,如果你愿意的话)。

于 2012-04-05T23:11:11.440 回答
1

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

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 调用它并只影响那个图片框。

于 2012-04-05T23:07:22.400 回答