【问题标题】:how to restrict child control inside Parent control in Winform application?如何在 Winform 应用程序的父控件中限制子控件?
【发布时间】:2013-08-26 04:37:31
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    您可以利用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;
        }
    

    【讨论】:

      【解决方案2】:

      如果您将标签动态添加到面板,那么您必须这样做:

      this.panel1.Controls.Add(this.button1);
      

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

      panel1.Location.X
      panel1.Location.Y
      

      如果需要,分享您的代码以获得更多帮助

      【讨论】:

        【解决方案3】:

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

        拖动时设置:

        Cursor.Clip = panel1.ClientRectangle;
        

        然后用 mouseUp 事件:

        Cursor.Clip = null;
        

        【讨论】:

        • 使用Cursor.Clip 的想法是可以的,但要使其成为 OP 想要的,我们需要更多的代码来处理。 Cursor.ClipRectangle,所以我们不能将其设置为 null
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-05
        • 1970-01-01
        • 2011-01-21
        • 1970-01-01
        • 2021-12-04
        相关资源
        最近更新 更多