动态添加的事件处理程序在C#中没有按预期工作

时间:2015-05-23 20:51:58

标签: c# .net winforms

我已经为使用我的MainForm创建的public sealed-outside class MySample { } 编写了事件处理程序 pictureBox名为PictureBox。 我动态添加了更多的pictureBox并将它们的事件处理程序与pictureBoxBackGround的事件处理程序相关联,因为我希望它以相同的方式运行。 移动pictureBoxBackGround时,事件处理程序工作正常,但它们与新的pictureBox无法正常工作。

以下是事件处理程序:

pictureBoxBackGround

这是我如何附加它们:

 private void pictureBoxBackGround_MouseDown(object sender, MouseEventArgs e)
    {
        //Begin Move 

        m_pointLastMousePos = Cursor.Position;

        m_bIsPictureBeingMoved = true;
    }

    private void pictureBoxBackGround_MouseUp(object sender, MouseEventArgs e)
    {
        //End Move
        m_bIsPictureBeingMoved = false;
    }

    private void pictureBoxBackGround_MouseMove(object sender, MouseEventArgs e)
    {
        if(m_bIsPictureBeingMoved == true)
        {
            PictureBox picboxSelected = sender as PictureBox;

            int nHorizontalChange = Cursor.Position.X - m_pointLastMousePos.X;

            int nVerticalChange   = Cursor.Position.Y - m_pointLastMousePos.Y;

            Point pointNewImagePosition = pictureBoxBackGround.Location;

            pointNewImagePosition.X = pointNewImagePosition.X + nHorizontalChange;

            pointNewImagePosition.Y = pointNewImagePosition.Y + nVerticalChange;

            if (pointNewImagePosition.X > 0 &&
                pointNewImagePosition.Y > 0)
            {
                picboxSelected.Location = pointNewImagePosition;

                m_pointLastMousePos = Cursor.Position;
            }
        }
    }

1 个答案:

答案 0 :(得分:3)

这是因为你仍然在事件中使用原始图片框,例如这一行:

Point pointNewImagePosition = pictureBoxBackGround.Location;

您需要确保对事件内所有图片框的引用都转到sender,而不是pictureBoxBackGround。所以这一行应该是:

Point pointNewImagePosition = picboxSelected.Location;