PictureBox在不应移动时移动

时间:2017-03-08 12:06:01

标签: c# winforms events mousemove mousedown

我对从PictureBox继承的自定义类有疑问。在OnMouseDown事件中,我将光标位置居中,在OnMouseMove事件中移动pictureBox

问题在于,当我居中光标的位置时,它也会移动pictureBox

我需要先将光标定位在pictureBox的中心,然后在移动光标时移动pictureBox

我尝试放置一个控制Click事件的bool,但它的行为方式一样。

pictureBox置于正确的Point

的方法
public void Colocar(Control control, Unidad unidad, Point p)
{
    unidad.Location = p;
    control.Controls.Add(unidad);
}

OnMouseDown事件处理程序:

bool clickPerformed = false; 
bool clickMove = false; //Para saber si hay que moverlo
private Point MouseDownLocation;
protected override void OnMouseDown(MouseEventArgs e)
{
    base.OnMouseDown(e);

    this.Cursor = new Cursor(Cursor.Current.Handle);
    Cursor.Position = new Point(this.Location.X + this.Size.Width / 2, this.Location.Y + this.Size.Height / 2);

    clickPerformed = true; 
    Control tempSender = this.Parent; 
    tempSender.Invalidate(); 
    MouseDownLocation = e.Location;
    clickMove = true;
}

OnMouseUp事件处理程序:

protected override void OnMouseUp(MouseEventArgs e)
{
    this.Parent.Invalidate();
    clickMove = false;
    base.OnMouseDown(e);
}

pictureBox

周围绘制圆圈的方法
public void DrawCircle(Graphics g, Pen pen, float centerX, float centerY, float radius)
{
    g.DrawEllipse(pen, centerX - radius, centerY - radius, radius + radius, radius + radius);
}

OnMouseMove事件处理程序:

protected override void OnMouseMove(MouseEventArgs e)
{
    base.OnMouseMove(e);
    if (clickMove)
    {
        Left = e.X + Left - MouseDownLocation.X;
        Top = e.Y + Top - MouseDownLocation.Y;
    }
}

0 个答案:

没有答案