最近看到一些 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(null, null);
}
[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;
}
}
}
}

代码在 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(null, null);
}
[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;
}
}
}
}

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

被折叠的 条评论
为什么被折叠?



