Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在Winform应用程序中将子控件限制在父控件内?_C#_.net_Winforms_C# 4.0 - Fatal编程技术网

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

C# 如何在Winform应用程序中将子控件限制在父控件内?,c#,.net,winforms,c#-4.0,C#,.net,Winforms,C# 4.0,我已经在面板控件中动态创建了标签控件。我正在使用鼠标事件移动标签控件。时间标签控件移动到面板控件之外。如何限制它?如果您将标签动态添加到面板,则必须执行以下操作: this.panel1.Controls.Add(this.button1); 如果你没有,那就是错误。除此之外,移动标签时,请确保新值在面板范围内,使用 panel1.Location.X panel1.Location.Y 如果需要,请共享您的代码以获取更多帮助您可以通过定义光标必须驻留的矩形来限制移动。使用该方法 拖动时设置

我已经在面板控件中动态创建了标签控件。我正在使用鼠标事件移动标签控件。时间标签控件移动到面板控件之外。如何限制它?

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

this.panel1.Controls.Add(this.button1);
如果你没有,那就是错误。除此之外,移动标签时,请确保新值在面板范围内,使用

panel1.Location.X
panel1.Location.Y

如果需要,请共享您的代码以获取更多帮助

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

拖动时设置:

Cursor.Clip = panel1.ClientRectangle;
然后使用mouseUp事件:

Cursor.Clip = null;

您可以根据自己的需求使用
Cursor.Clip
(尽管我们可以在
MouseMove
事件处理程序中手动处理此问题):


使用
Cursor.Clip
的想法是可以的,但是要使它成为OP想要的,我们需要更多的代码来处理
Cursor.Clip
是一个
矩形
,因此无法将其设置为
null
    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;
    }