我正在创建一个应用程序,可以在其中移动Labels
上的PictureBox
。
问题是我只希望这些标签在PictureBox
内 内移动。
这是我的代码:
protected void lbl_MouseMove(object sender, MouseEventArgs e)
{
Label lbl = sender as Label;
try
{
if (lbl != null && e.Button == MouseButtons.Left)
{
if (m_lblLocation != new Point(0, 0))
{
Point newLocation = lbl.Location;
newLocation.X = newLocation.X + e.X - m_lblLocation.X;
newLocation.Y = newLocation.Y + e.Y - m_lblLocation.Y;
lbl.Location = newLocation;
this.Refresh();
}
}
}
catch(Exception ex) { }
}
protected void lbl_MouseUp(object sender, MouseEventArgs e)
{
Label lbl = sender as Label;
try
{
if (lbl != null && e.Button == MouseButtons.Left)
{
m_lblLocation = Point.Empty;
}
}
catch(Exception ex) { }
}
protected void lbl_MouseDown(object sender, MouseEventArgs e)
{
Label lbl = sender as Label;
try
{
if (lbl != null && e.Button == MouseButtons.Left)
{
m_lblLocation = e.Location;
}
}
catch(Exception ex) { }
}
在上面的代码中,我为标签创建了一些鼠标事件。
答案 0 :(得分:2)
PictureBox
控件不是容器,您不能像在Panel
,{{1} }或其他实现IContainerControl
的控件。
您可以为GroupBox
设置父级(在这种情况下),将Label
父级设置为Label
句柄。 PictureBox
随后将反映父级Label.Bounds
。
但是,这不是必需的:您只需计算相对于同时包含(Bounds
(s)和Label
)的控件的Label位置:
您可以限制订阅PictureBox
事件的其他Label
控件的移动。
一个例子:
MovableLabel_MouseDown/MouseUp/MouseMove
答案 1 :(得分:0)
您需要跟踪两件事:
1.是否按下鼠标-bool IsMouseDown = false;
2.标签的起始位置-Point StartPoint;
// mouse is not down
private void label1_MouseUp(object sender, MouseEventArgs e)
{
IsMouseDown = false;
}
//mouse is down and set the starting postion
private void label1_MouseDown(object sender, MouseEventArgs e)
{
//if left mouse button was pressed
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
IsMouseDown = true;
label1.BringToFront();
StartPoint = e.Location;
}
}
//check the label is withing the borders of the picture box
private void label1_MouseMove(object sender, MouseEventArgs e)
{
if (IsMouseDown)
{
int left = e.X + label1.Left - StartPoint.X;
int right = e.X + label1.Right - StartPoint.X;
int top = e.Y + label1.Top - StartPoint.Y;
int bottom = e.Y + label1.Bottom - StartPoint.Y;
if (left > pictureBox1.Left && top > pictureBox1.Top && pictureBox1.Bottom >= bottom && pictureBox1.Right >= right)
{
label1.Left = left;
label1.Top = top;
}
}
}