Saturday, September 30, 2006

To collapse and hide a section of code in Visual Studio 2005

The #Region directive enables you to collapse and hide sections of code in Visual Basic files. The #Region directive lets you specify a block of code that you can expand or collapse when using the Visual Studio code editor. The ability to hide code selectively makes your files more manageable and easier to read. For more information, see How to: Outline and Hide Code.

#Region directives support code block semantics such as #If...#End If. This means they cannot begin in one block and end in another; the start and end must be in the same block. #Region directives are not supported within functions.

To collapse and hide a section of code
Place the section of code between the #Region and #End Region statements, as in the following example:

#Region "This is the code to be collapsed"
Private components As System.ComponentModel.Container
Dim WithEvents Form1 As System.Windows.Forms.Form

Private Sub InitializeComponent()
components = New System.ComponentModel.Container
Me.Text = "Form1"
End Sub
#End Region


The #Region block can be used multiple times in a code file; thus, users can define their own blocks of procedures and classes that can, in turn, be collapsed. #Region blocks can also be nested within other #Region blocks.

Note
Hiding code does not prevent it from being compiled and does not affect #If...#End If statements.

^ 在一个method范围内是不能使用Region的,如果要实现“收起放开”,需要使用CTRL+M and then CTRL+H以及CTRL+M and then CTRL+U.

@ Hide Selection
Collapses the currently selected text. Text must be selected to use this command. Shortcut keys are CTRL+M and then CTRL+H.

@ Stop Hiding Current
Removes the outlining information for the currently selected user-defined region. Shortcut keys are CTRL+M and then CTRL+U.
Note This command becomes available in Visual C# and Visual J# when Automatic Outlining is turned off or Stop Outlining is selected. Not available in Visual Basic.