Skip to main content
 首页 » 编程设计

c#之检查面板是否包含某些东西

2024年02月06日16jirigala

private void PBoxJigsaw1_MouseUp(object sender, MouseEventArgs e) 
    { 
        if (sender != null && sender.GetType() == typeof(PictureBox)) 
        { 
            if (e.Button == System.Windows.Forms.MouseButtons.Left) 
            { 
                PictureBox answer = (PictureBox)sender; 
 
                if (answer.Location.X < pnlJigsaw5.Location.X && answer.Location.Y > pnlJigsaw5.Location.Y) 
                { 
                    if (answer.Location.X + answer.Width > pnlJigsaw5.Location.X) 
                    { 
                        if ((answer.Location.X + answer.Width) < pnlJigsaw5.Location.X + pnlJigsaw5.Width) 
                        { 
                            answer.Location = pnlJigsaw5.Location; 
                        } 
                    } 
                } 
                else if (answer.Location.X < pnlJigsaw1.Location.X && answer.Location.Y > pnlJigsaw1.Location.Y) 
                { 
                    if (answer.Location.X + answer.Width > pnlJigsaw1.Location.X) 
                    { 
                        if ((answer.Location.X + answer.Width) < pnlJigsaw1.Location.X + pnlJigsaw1.Width) 
                        { 
                            answer.Location = pnlJigsaw1.Location; 
                        } 
                    } 
                } 

我在 C# 上创建了一个拼图,用户可以在其中将图片框拖到面板中以创建图像。我想知道是否有可能检查一个面板是否包含某些东西,因为在许多图片框可以进入一个面板的那一刻,它们看起来好像消失了,尽管它们只是彼此落后。我只是想让面板中一次只能有一个 pictureBox。谢谢

请您参考如下方法:

您可以检查您要放置 pictureBox 的面板是否包含任何控件

if(panel.Controls.Count > 0) 
{ 
  // Panel contains items inside 
  // Ignore Panel 
} 

编辑1: 您是否尝试将此代码放在事件的顶部?像这样

private void PBoxJigsaw1_MouseUp(object sender, MouseEventArgs e) 
{ 
    if(panel.Controls.Count > 0)  
    { 
        return; // Panel already contains a control, stop executing the code 
    } 
 
    if (sender != null && sender.GetType() == typeof(PictureBox)) 
    { 
        .... 

这会使图片框消失吗?