我正在创建一个应用程序,可以在其中移动PictureBox
上的Labels
。
问题是我希望这些标签只在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) { }
}
字符串
在上面的代码中,我为标签创建了一些鼠标事件。
2条答案
按热度按时间7lrncoxx1#
PictureBox
控件不是一个容器,你不能直接把另一个控件放在它里面,就像你对Panel
,GroupBox
或其他实现IContainerControl
的控件所做的那样。您可以将
Label
设置为父对象(在本例中),将Label
Parent设置为PictureBox
句柄。然后Label.Bounds
将反映父Bounds
。但这不是必须的:你可以只计算标签相对于同时包含(
Label
(s)和PictureBox
)的控件的位置:您可以限制订阅
MovableLabel_MouseDown/MouseUp/MouseMove
事件的其他Label
控件的移动。举个例子:
字符串
的数据
ao218c7q2#
你需要追踪两件事1.鼠标是否按下-
bool IsMouseDown = false;
2.标签的起始位置-Point StartPoint;
字符串