The Visual Basic Code Editor


Visual Studio includes editors for many different kinds of documents, including several different kinds of code. For example, it has Hypertext Markup Language (HTML), Extensible Markup Language (XML), and Visual Basic editors. These editors share some common features, such as displaying comments and keywords in different colors.

As a Visual Basic developer, you will use the Visual Basic code editor frequently, so you should spend a few minutes learning about its specialized features.

Figure 1-54 shows the code editor displaying some Visual Basic code at runtime. To make referring to the code lines easier, this figure displays line numbers. To display line numbers, invoke the Tools menu’s Options command, navigate to the Text Editor image from book Basic image from book General page, and check the Line Numbers box.

image from book
Figure 1-54: The Visual Basic code editor provides many features, including line numbers and icons that indicate breakpoints and bookmarks.

Margin Icons

The gray margin to the left of the line numbers contains icons giving information about the corresponding lines of code. The following table describes the icons on lines 4 through 13.

Open table as spreadsheet

Line

Icon

Meaning

4

Yellow arrow

Indicates that execution is paused at this line

5

Red circle

Indicates a breakpoint

6

Hollow red circle

Indicates a disabled breakpoint

7

Red circle with plus sign

Indicates a breakpoint with a condition or hit count test

10

Red diamond

Indicates a breakpoint that executes an action when reached

11

Blue and white rectangle

Indicates a bookmark

These icons can combine to indicate more than one condition. For example, line 12 shows a blue and white rectangle to indicate a bookmark, a hollow red diamond to indicate a disabled breakpoint that performs an action, and a plus sign to indicate that the breakpoint has a condition or hit count test.

Note that the editor marks some of these lines in other ways than just an icon. It highlights the currently executing line with a yellow background. It marks lines that hold enabled breakpoints with white text on a red background.

To add or remove a simple breakpoint, click in the gray margin.

To make a more complex breakpoint, click in the margin to create a simple breakpoint. Then right-click the breakpoint icon and select one of the context menu’s commands. The following list describes these commands:

  • Delete Breakpoint - Removes the breakpoint.

  • Disable Breakpoint - Disables the breakpoint. When the breakpoint is disabled, this command changes to Enable Breakpoint.

  • Location - Lets you change the breakpoint’s line number. Usually it is easier to click in the margin to remove the old breakpoint and then create a new one.

  • Condition - Lets you place a condition on the breakpoint. For example, you can make the breakpoint stop execution only when the variable num_employees has a value greater than 100.

  • Hit Count - Lets you set a hit count condition on the breakpoint. For example, you can make the breakpoint stop execution when it has been reached a certain number of times.

  • Filter - Lets you restrict the breakpoint so it is only set in certain processes or threads.

  • When Hit - Lets you specify the action that the breakpoint performs when it triggers. For example, it might display a message in the Output window or run a macro.

To add or remove a bookmark, place the cursor on a line and then click the Toggle Bookmark tool. You can find this tool, which looks like the blue and white bookmark icon, in the Text Editor toolbar (under the mouse in Figure 1-54) and at the top of the Bookmarks window. Other bookmark tools let you move to the next or previous bookmark, the next or previous bookmark in the current folder, or the next or previous bookmark in the current document. The final bookmark command clears all bookmarks.

Outlining

By default, the code editor displays an outline view of code. If you look at the first line in Figure 1-53, you’ll see a box with a minus sign in it just to the right of the line number. That box represents the outlining for the Form1 class. If you click this box, the editor collapses the class’s definition and displays it as a box containing a plus sign. If you then click the new box, the editor expands the class’s definition again.

The gray line leading down from the box leads to other code items that are outlined, and that you can expand or collapse to give you the least cluttered view of the code you want to examine. Near the bottom of Figure 1-54, you can see that the RandomizeArray subroutine has been collapsed. The ellipsis and rectangle around the routine name provide an extra indication that this code is hidden.

The editor automatically creates outlining entries for namespaces, classes and their methods, and modules and their methods. You can also use the Region statement to group a section of code for outlining.

For example, you can place several related subroutines in a region so you can collapse and expand the routines as a group.

Figure 1-55 shows more examples of outlining. Line 36 begins a region named Randomization Functions that contains three collapsed subroutines. Notice that the corresponding End Region statement includes a comment giving the region’s name. This is not required but it makes the code easier to understand when you are looking at the end of a region.

image from book
Figure 1-55: The code editor outlines namespaces, classes and their methods, modules and their methods, and regions.

Line 89 contains a collapsed region named Utility Functions.

Line 95 starts a module named HelperRoutines that contains one collapsed subroutine.

Finally, Line 114 holds the collapsed ImageResources namespace.

Notice that the line numbers skip values for any collapsed lines. For example, the RandomizeIntegerArray subroutine is collapsed on line 38. This subroutine contains 15 lines (including the Sub statement), so the next visible line is labeled 53.

Also notice that comments before a subroutine are not collapsed with the subroutine. You can make reading collapsed code easier by placing a short descriptive comment before each routine.

Tooltips

If you hover the mouse over a variable at design time, the editor displays a tooltip describing the variable. For example, if you hovered over an integer variable named num_actions, the tooltip would display “Dim num_actions As Integer.”

If you hover over a subroutine or function call, the tooltip displays information about that method. For example, if you hover over the RandomizeArray subroutine (which takes an array of integers as a parameter), the tooltip will read, “Private Sub RandomizeArray(arr() As Integer).”

At runtime, if you hover over a variable, the tooltip displays the variable’s value. If the variable is complex (such as an array or structure), the tooltip displays the variable’s name and a plus sign. If you click or hover over the plus sign, the tooltip expands to show the variable’s members.

In Figure 1-56, the mouse hovered over variable arr. The editor displayed a plus sign and the text arr {Length = 100}. When the mouse hovered over the plus sign, the editor displayed the values shown in the figure. Moving the mouse over the up and down arrows at the top and bottom of the list makes the values scroll.

image from book
Figure 1-56: You can hover the mouse over a variable at run time to see its value.

If a variable has properties that are references to other objects, you can hover over their plus signs to expand those objects. You can continue following the plus signs to drill into the variable’s object hierarchy as deeply as you like.

IntelliSense

If you start typing a line of code, the editor tries to anticipate what you will type. For example, if you typed Me. then the editor would know that you are about to use one of the current object’s properties or methods.

IntelliSense displays a list of the properties and methods that you might be trying to select. As you type more of the property or method, IntelliSense scrolls to show the choices that match what you have typed.

In Figure 1-57, the code includes the text me.Set, so IntelliSense is displaying the current object’s methods that begin with the string Set.

image from book
Figure 1-57: IntelliSense displays a list of properties and methods that you might be trying to type.

While the IntelliSense window is visible, you can use the up and down arrows to scroll through the list. While IntelliSense is displaying the item that you want to use, you can press the Tab key to accept that item. Press the Escape key to close the IntelliSense window and type the rest manually.

After you finish typing a method and its opening parenthesis, IntelliSense displays information about the method’s parameters. Figure 1-58 shows parameter information for a form object’s SetBounds method. This method takes four parameters: x, y, width, and height.

IntelliSense shows a brief description of the current parameter x. As you enter parameter values, IntelliSense moves on to describe the other parameters.

IntelliSense also indicates whether there are overloaded versions of the method. In Figure 1-58, IntelliSense is describing the first version of two available versions. You can use the up and down arrows on the left to move through the list of overloaded versions.

image from book
Figure 1-58: IntelliSense displays information about a method’s parameters.

Code Coloring and Highlighting

The code editor displays different types of code items in different colors. You can change the colors used for different items by selecting the Tools menu’s Options command, and opening the Environment image from book Fonts and Colors option page. To avoid confusion, however, you should probably leave the colors alone unless you have a good reason to change them.

The following table describes some of the default colors that the code editor uses to highlight different code elements.

Open table as spreadsheet

Item

Highlighting

Comment

Green text

Compiler error

Underlined with a wavy blue underline

Keyword

Blue text

Other error

Underlined with a wavy purple underline

Preprocessor keyword

Blue text

Read-only region

Light gray background

Stale code

Purple text

User types

Navy text

Warning

Underlined with a wavy green underline

A few other items that may be worth changing have white backgrounds and black text by default. These include identifiers (variable names, types, object properties and methods, namespace names, and so forth), numbers, and strings.

When the code editor finds an error in your code, it highlights the error with a wavy underline. If you hover over the underline, the editor displays a tooltip describing the error. If Visual Studio can guess what you are trying to do, it adds a small flat rectangle to the end of the wavy error line to indicate that it may have useful suggestions.

The assignment statement i = “12” shown in Figure 1-59 has an error because it tried to assign a string value to an integer variable and that violates the Option Strict On setting. The editor displays the wavy error underline and a suggestion indicator because it knows a way to fix this error. The Error List window at the bottom also shows a description of the error.

image from book
Figure 1-59: If the code editor can figure out what’s wrong, it displays a suggestion indicator.

If you hover over the suggestion indicator, the editor displays a tooltip describing the problem and an error icon. If you click the icon, Visual Studio displays a dialog box describing the error and listing the actions that you may want to take. Figure 1-60 shows the suggestion dialog box for the error in Figure 1-59. If you click the text over the revised sample code, or if you double-click the sample code, the editor makes the change.

image from book
Figure 1-60: The error suggestion dialog box proposes likely solutions to an error.

Code Snippets

A code snippet is a piece of code that you might find useful in many applications. It is stored in a snippet library so that you can quickly insert it into a new application.

Visual Studio comes with hundreds of snippets for performing standard tasks. Before you start working on a complicated piece of code, you should take a look at the snippets that are already available to you. In fact, it would be worth your time to use the Snippet Manager available from the Tools menu to take a good look at the available snippets right now before you start a new project. There’s little point in you reinventing methods for calculating statistical values if someone has already done it and given you the code.

Snippets are stored in simple text files with XML tags, so it is easy to share snippets with other developers. Go to this book’s web page, www.vb-helper.com/vbprogref.htm, to contribute snippets and to download snippets contributed by others.

The following sections explain how to use snippets in your applications and how to create new snippets.

Using Snippets

To insert a snippet, right-click where you want to insert the code and select Insert Snippet to make the editor display a list of snippet categories. Double-click a category to find the kinds of snippets that you want. If you select a snippet, a tooltip pops up to describe it. Figure 1-61 shows the editor preparing to insert the snippet named Create a public property from the VbProgRef Code Snippets category.

image from book
Figure 1-61: When you select a code snippet, a pop-up describes it.

Double-click the snippet to insert it into your code. The snippet may include values that you should replace in your code. These replacement values are highlighted with a light green background, and the first value is initially selected. If you hover the mouse over one of these values, a tooltip appears to describe the value. You can use the Tab key to jump between replacement values.

Figure 1-62 shows the inserted code for this example. The text An Integer Property is highlighted and selected. Other selected text includes Integer, 0, and MyProperty. The mouse is hovering over the value An Integer Property, so the tooltip explains that value’s purpose.

image from book
Figure 1-62: Values that you should replace in a snippet are highlighted.

Creating Snippets

To create a new snippet, you need to build an XML file containing the property tags to define the snippet and any replacements that the user should make. The following code shows the Create a public property snippet used in the previous section. The outer CodeSnippets and CodeSnippet tags are standard and you should not change them.

Use the Title tag in the Header section to describe the snippet.

Inside the Snippet tag, build a Declarations section describing any literal text that the user should replace. This example defines DataType, Description, DefaultValue, and PropertyName symbols. Each literal definition includes an ID, and can include a ToolTip and Description.

After the declarations, the Code tag contains the snippets source code. The syntax <![CDATA[...]]> tells XML processors to include any characters including carriage returns between the <![CDATA[ and the ]]> in the enclosing tag.

  <CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">     <CodeSnippet Format="1.0.0">         <Header>             <Title>Create a public property</Title>         </Header>         <Snippet>             <Declarations>                 <Literal>                     <ID>DataType</ID>                     <ToolTip>The property's data type.</ToolTip>                     <Default>Integer</Default>                 </Literal>                 <Literal>                     <ID>Description</ID>                     <ToolTip>The property's description.</ToolTip>                     <Default>An Integer property.</Default>                 </Literal>                 <Literal>                     <ID>DefaultValue</ID>                     <ToolTip>The property's default value.</ToolTip>                     <Default>0</Default>                 </Literal>                 <Literal>                     <ID>PropertyName</ID>                     <ToolTip>The property's name.</ToolTip>                     <Default>MyProperty</Default>                 </Literal>             </Declarations>             <Code Language="VB">                 <![CDATA [     ' $Description$     Private m_$PropertyName$As $DataType$=$DefaultValue$     Public Property $PropertyName$()As $DataType$         Get             Return m_$PropertyName$         End Get         Set(ByVal value As $DataType$)             m_$PropertyName$=value         End Set     End Property ]]>             </Code>         </Snippet>     </CodeSnippet> </CodeSnippets> 

Save the snippet’s XML definition in a snippet directory. To add the directory to the list of usable snippet locations, select the Tool menu’s Code Snippets Manager command to display the tool shown in Figure 1-63. Click the Add button, browse to the new snippet directory, and click OK. Now the directory and the snippets that it contains will be available in the Insert Snippet pop-ups.

image from book
Figure 1-63: The Code Snippets Manager lets you add and remove snippet directories.

The Code Editor at Runtime

The code editor behaves slightly differently at runtime and design time. Many of its design time features still work. Breakpoints, bookmarks, IntelliSense, and snippets still work.

At runtime, the editor adds new tools for controlling the program’s execution. Right-click a value and select Add Watch or QuickWatch to examine and monitor the value. Use the Stop Into, Step Over, and Step Out commands on the Debug menu or toolbar to make the program walk through the code.

Right-click a statement and select Show Next Statement to move the cursor to the next statement that the program will execute. Select Run To Cursor to make the program continue running until it reaches the cursor’s current line.

Right-click and select Set Next Statement to make the program jump to a new location. You can also drag the yellow arrow indicating the next statement to a new location in the left margin. There are some restrictions on where you can move the execution position. For example, you cannot jump out of one routine and into another.

You can discover other runtime features by exploring the editor at run time. Right-click on different parts of the editor to see which commands are available in that mode.




Visual Basic 2005 with  .NET 3.0 Programmer's Reference
Visual Basic 2005 with .NET 3.0 Programmer's Reference
ISBN: 470137053
EAN: N/A
Year: 2007
Pages: 417

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net