如何限制控件在另一个控件范围内的移动

2024-02-04

我正在创建一个应用程序,我可以在其中移动Labels位于PictureBox.
问题是我希望这些只移动标签inside the 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) { }
}

在上面的代码中,我为标签创建了一些鼠标事件。


The PictureBox控件不是容器,不能直接放入另一个控件inside它,就像你会做的Panel, a GroupBox或其他实现的控件IContainerControl https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.icontainercontrol.
您可以为Label(在本例中),设置Label父级为PictureBox处理。这Label.Bounds然后将反映父母Bounds.
但这不是必需的:您可以只计算标签相对于包含两者的控件的位置(Label(s) and PictureBox):

可以限制其他人的行动Label控制订阅MovableLabel_MouseDown/MouseUp/MouseMove events.

一个例子:

bool thisLabelCanMove;
Point labelMousePosition = Point.Empty;

private void MovableLabel_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left) {
        labelMousePosition = e.Location;
        thisLabelCanMove = true;
    }
}

private void MovableLabel_MouseUp(object sender, MouseEventArgs e)
{
    thisLabelCanMove = false;
}

private void MovableLabel_MouseMove(object sender, MouseEventArgs e)
{
    if (thisLabelCanMove) {
        var label = sender as Label;

        Point newLocation = new Point(label.Left + (e.Location.X - labelMousePosition.X),
                                      label.Top + (e.Location.Y - labelMousePosition.Y));
        newLocation.X = (newLocation.X < pictureBox1.Left) ? pictureBox1.Left : newLocation.X;
        newLocation.Y = (newLocation.Y < pictureBox1.Top) ? pictureBox1.Top : newLocation.Y;
        newLocation.X = (newLocation.X + label.Width > pictureBox1.Right) ? label.Left : newLocation.X;
        newLocation.Y = (newLocation.Y + label.Height > pictureBox1.Bottom) ? label.Top : newLocation.Y;
        label.Location = newLocation;
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何限制控件在另一个控件范围内的移动 的相关文章

随机推荐