挖一下 SuspendLayout, ResumeLayout 的原理

本文探讨了在WinForm开发中,使用SuspendLayout和ResumeLayout方法来控制控件布局更新的原因。通过Reflector查看System.Windows.Forms.Control源码,了解到这两个方法在控件布局更新管理中的作用,以及它们如何影响DockStyle设置和子控件添加。当SuspendLayout增加布局暂停计数,而ResumeLayout则减少计数,并在计数为0时决定是否执行PerformLayout以更新布局。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近看到一些 winform 控件的写法里面,在设定 DockStyle 或者增减子控件的时候,往往先调用 SuspendLayout 方法,操作完毕之后调用一下 ResumeLayout. 不太明白其中的道理。所以用 Reflector 来看一下。
代码在 System.Windows.Forms.Control 中。
做一个简单的记录如下:

public void SuspendLayout()
{
      
this.layoutSuspendCount = (byte) (this.layoutSuspendCount + 1);
}


public void ResumeLayout()
{
      
this.ResumeLayout(true);
}
 

public void ResumeLayout(bool performLayout)
{
      
if (this.layoutSuspendCount > 0)
      
{
            
this.layoutSuspendCount = (byte) (this.layoutSuspendCount - 1);
            
if (((this.layoutSuspendCount == 0&& ((this.state & 0x200!= 0)) && performLayout)
            
{
                  
this.PerformLayout();
            }

      }

      
if (!performLayout)
      
{
            Control.ControlCollection collection1 
= (Control.ControlCollection) this.Properties.GetObject(Control.PropControlsCollection);
            
if (collection1 != null)
            
{
                  
for (int num1 = 0; num1 < collection1.Count; num1++)
                  
{
                        Control.LayoutManager.UpdateAnchorInfo(collection1[num1]);
                  }

            }

      }

}

 
[EditorBrowsable(EditorBrowsableState.Advanced)]
public void PerformLayout()
{
      
this.PerformLayout(nullnull);
}

 
[EditorBrowsable(EditorBrowsableState.Advanced)]
public void PerformLayout(Control affectedControl, string affectedProperty)
{
      
if (!this.GetAnyDisposingInHierarchy())
      
{
            
if (this.layoutSuspendCount > 0)
            
{
                  
this.state |= 0x200;
            }

            
else
            
{
                  
this.layoutSuspendCount = 1;
                  
try
                  
{
                        
this.OnLayout(new LayoutEventArgs(affectedControl, affectedProperty));
                  }

                  
finally
                  
{
                        
this.state &= -513;
                        
this.layoutSuspendCount = 0;
                  }

            }

      }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值