Tip: SuspendLayout and ResumeLayout in Office Applications
When you develop WinForm applications, and you want to update various UI elements, it'd be better to call Form.SuspendLayout before the updates and Form.ResumeLayout after the updates.
When developing in Office environment, you don't have these methods... But it doesn't mean that you can't achieve the exact behavior!
When you want to suspend the layout, execute the following line of code:
Application.ScreenUpdating = false;
When you want to resume the layout, execute:
Application.ScreenUpdating = true;
That's it!
WARNING: if you set the ScreenUpdating to false and never set it to true again, your office application editing surface will freeze and the user will have to restart the application... I've come up with a solution for that. Add the following class to your application:
public class ScreenSuspender : IDisposable
{
public static IDisposable SuspendLayout()
{
return new ScreenSuspender();
}
private ScreenSuspender()
{
Globals.ThisDocument.Application.ScreenUpdating = false;
}
public void Dispose()
{
Globals.ThisDocument.Application.ScreenUpdating = true;
}
}
Pay attention that this code is for a VSTO Word document. Other office applications might require small adjustments for it to work.
Now when you want to suspend and resume the document layout, all you have to do is:
using (ScreenSuspender.SuspendLayout())
{
// do some layout changes
}
This will make sure your Office application doesn't freeze, even if the code inside the using block fails to execute.
All the best,
Shay.