我遇到了拖放问题。我有代码:
void labelWorker_MouseEvent(object sender, MouseEventArgs e)
{
Label labelWorker = (Label)sender;
labelWorker.DoDragDrop(labelWorker, DragDropEffects.Move);
labelWorker.MouseDown += new MouseEventHandler(labelWorker_MouseDown);
labelWorker.MouseMove += new MouseEventHandler(labelWorker_MouseMove);
labelWorker.MouseUp += new MouseEventHandler(labelWorker_MouseUp);
}
bool isDragged = false;
Point ptOffset;
void labelWorker_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Label labelWorker = (Label)sender;
isDragged = true;
Point ptStartPosition = labelWorker.PointToScreen(new Point(e.X, e.Y));
ptOffset = new Point();
ptOffset.X = labelWorker.Location.X - ptStartPosition.X;
ptOffset.Y = labelWorker.Location.Y - ptStartPosition.Y;
}
else
{
isDragged = false;
}
}
void labelWorker_MouseMove(object sender, MouseEventArgs e)
{
Label labelWorker = (Label)sender;
if (isDragged)
{
Point newPoint = labelWorker.PointToScreen(new Point(e.X, e.Y));
newPoint.Offset(ptOffset);
labelWorker.Location = newPoint;
}
}
void labelWorker_MouseUp(object sender, MouseEventArgs e)
{
Label labelWorker = (Label)sender;
isDragged = false;
}
当我尝试移动它时,标签开始吓坏了。我认为问题在于
void labelWorker_MouseMove(object sender, MouseEventArgs e)
{
Label labelWorker = (Label)sender;
if (isDragged)
{
Point newPoint = labelWorker.PointToScreen(new Point(e.X, e.Y));
newPoint.Offset(ptOffset);
labelWorker.Location = newPoint;
}
}
答案 0 :(得分:0)
确定。我刚刚做到了:)
bool clicked = false;
int iOldX;
int iOldY;
int iClickX;
int iClickY;
void labelWorker_MouseDown(object sender, MouseEventArgs e)
{
Label labelWorker = (Label)sender;
if (e.Button == MouseButtons.Left)
{
Point p = ConvertFromChildToForm(e.X, e.Y, labelWorker);
iOldX = p.X;
iOldY = p.Y;
iClickX = e.X;
iClickY = e.Y;
clicked = true;
}
}
void labelWorker_MouseMove(object sender, MouseEventArgs e)
{
Label labelWorker = (Label)sender;
if (clicked)
{
Point p = new Point(); // New Coordinate
p.X = e.X + labelWorker.Left;
p.Y = e.Y + labelWorker.Top;
labelWorker.Left = p.X - iClickX;
labelWorker.Top = p.Y - iClickY;
}
}
void labelWorker_MouseUp(object sender, MouseEventArgs e)
{
clicked = false;
}
private Point ConvertFromChildToForm(int x, int y, Control control)
{
Point p = new Point(x, y);
control.Location = p;
return p;
}