如何在Winform应用程序中限制父控件内的子控件?

时间:2013-08-26 04:37:31

标签: c# .net winforms c#-4.0

我在Panel控件中动态创建了Label控件。我正在使用鼠标事件移动标签控件。那个时间标签控制移动到面板控制之外。我怎么能限制它?

3 个答案:

答案 0 :(得分:3)

您可以将Cursor.Clip的好处用于您的要求(尽管我们可以在MouseMove事件处理程序中手动处理):

    Point downPoint;
    //MouseDown event handler for your label1
    private void label1_MouseDown(object sender, MouseEventArgs e){
        downPoint = e.Location;
        //this is the most important code to make it works
        Cursor.Clip = yourPanel.RectangleToScreen(new Rectangle(e.X, e.Y, yourPanel.ClientSize.Width - label1.Width, yourPanel.ClientSize.Height - label1.Height));
    }
    //MouseMove event handler for your label1
    private void label1_MouseMove(object sender, MouseEventArgs e) {
        if (e.Button == MouseButtons.Left) {
            label1.Left += e.X - downPoint.X;
            label1.Top += e.Y - downPoint.Y;
        }
    }
    //MouseUp event handler for your label1
    private void label1_MouseUp(object sender, MouseEventArgs e){
        Cursor.Clip = Rectangle.Empty;
    }

答案 1 :(得分:1)

如果您动态地将标签添加到面板,则必须执行以下操作:

this.panel1.Controls.Add(this.button1);
如果你不这样做,那就是错误。最重要的是,当您移动标签时,请确保新值在面板范围内,使用

panel1.Location.X
panel1.Location.Y

并在需要时分享您的代码以获得更多帮助

答案 2 :(得分:1)

您可以通过定义光标必须驻留的矩形来限制移动。使用Cursor.Clip方法。

拖动时设置:

Cursor.Clip = panel1.ClientRectangle;

然后使用mouseUp事件:

Cursor.Clip = null;