Share via


Visual Studio 2005 IDE Tips and Tricks

 

James Lau
Program Manager, Microsoft

December 2006

Applies to:
   Microsoft Visual Studio 2005

Summary: Visual Studio 2005 is the leading developer tool on the market, and I would like to share with you some tips and tricks that will make this great tool even more powerful. Getting familiar with a tool is crucial to getting the most out of the tool, and development tools and IDEs are no different. But with the many new technologies such as C# 2.0, ASP .NET 2.0, Windows Workflow Foundation, Windows Presentation Foundation, and Windows Communication Foundation, who has time to learn about Visual Studio itself? By spending 10 minutes to read this article, I hope you will learn a couple of useful things that will make your life inside Visual Studio more pleasant and productive. (19 printed pages)

Contents

Keeping Your Hands on the Keyboard
Window Layout Selector
Code Snippets
Customizing Visual Studio Start Page
Team Settings
/resetuserdata Switch
Conclusion

Keeping Your Hands on the Keyboard

My favorite keyboard shortcuts

Ever wished that you never have to take your hands off the keyboard when you are doing your development inside Visual Studio? If you are a power user, you will certainly enjoy the using keyboard shortcuts to perform various operations more quickly. I am sure most of you are already familiar with some of them: F5 for Debug.Start, F10 for Debug.StepOver, F4 for View.Properties. There are several other very useful keyboard shortcuts that are less known. I have included some of my favorite ones in the table below.

Keyboard Shortcut Command
F7 Toggles between design and code views.
F9 Toggles breakpoint.
F12 Go to definition of a variable, object, or function.
Ctrl+Shift+7

Ctrl+Shift+8

Quickly navigate forward and backwards in the go to definition stack.
Shift+F12 Find all references of a function or a variable.
Ctrl+M, Ctrl+M Expand and collapse code outlining in the editor.
Ctrl+K, Ctrl+C

Ctrl+K, Ctrl+U

Comment and uncomment line(s) of code, respectively.
Shift+Alt+Enter Toggles between full screen mode and normal mode.
Ctrl+I Incremental Search.

Creating a keyboard shortcuts cheat sheet

Most people don't know this, but there are actually over 450 keyboard shortcuts in Visual Studio by default. But there is no easy way to find out all the keyboard shortcuts inside Visual Studio. You can find out what all the default keyboard shortcuts are by writing a simple macro to enumerate all of them. The following (Listing 1) shows the code for this.

Public Module Module1

    Public Sub ListShortcutsInHTML()

        'Declare a StreamWriter
        Dim sw As System.IO.StreamWriter
        sw = New StreamWriter("c:\\demo\\Shortcuts.html")

        'Write the beginning HTML
        WriteHTMLStart(sw)

        ' Add a row for each keyboard shortcut
        For Each c As Command In DTE.Commands
            If c.Name <> "" Then
                Dim bindings As System.Array
                bindings = CType(c.Bindings, System.Array)
                For i As Integer = 0 To bindings.Length - 1
                    sw.WriteLine("<tr>")
                    sw.WriteLine("<td>" + c.Name + "</td>")
                    sw.WriteLine("<td>" + bindings(i) + "</td>")
                    sw.WriteLine("</tr>")
                Next

            End If
        Next

        'Write the end HTML
        WriteHTMLEnd(sw)

        'Flush and close the stream
        sw.Flush()
        sw.Close()
    End Sub
Public Sub WriteHTMLStart(ByVal sw As System.IO.StreamWriter)
        sw.WriteLine("<html>")
        sw.WriteLine("<head>")
        sw.WriteLine("<title>")

        sw.WriteLine("Visual Studio Keyboard Shortcuts")
        sw.WriteLine("</title>")
        sw.WriteLine("</head>")

        sw.WriteLine("<body>")
        sw.WriteLine("<h1>Visual Studio 2005 Keyboard Shortcuts</h1>")
        sw.WriteLine("<font size=""2"" face=""Verdana"">")
        sw.WriteLine("<table border=""1"">")
        sw.WriteLine("<tr BGCOLOR=""#018FFF""><td 
align=""center""><b>Command</b></td><td 
align=""center""><b>Shortcut</b></td></tr>")


    End Sub

    Public Sub WriteHTMLEnd(ByVal sw As System.IO.StreamWriter)
        sw.WriteLine("</table>")
        sw.WriteLine("</font>")
        sw.WriteLine("</body>")
        sw.WriteLine("</html>")
    End Sub

End Module

Listing 1. Macro to generate Keyboard Shortcuts in HTML

To use this macro, go to Tools, select Macros, and then choose Macros IDE. . . to launch the Macros IDE. Expand the MyMacros project, MyMacros namespace and double-click on Module1. Simply copy Listing 1 to the Macros IDE and run the macro. After running the macro, you would have produced a keyboard shortcuts reference for Visual Studio. Open your output at C:\demo\Shortcuts.html. Figure 1 shows the partial output. Feel free to print it out and post it near your computer as you learn new keyboard shortcuts.

Bb245788.vs05idetips1s(en-US,VS.80).gif

Figure 1. Partial listing of Visual Studio 2005 Keyboard Shortcuts

Customizing Keyboard Shortcuts

If you have a favorite keyboard shortcut that is not mapped by default, you can always customize it through by clicking Tools > Options... > Environment > Keyboard (see Figure 2). However, if you add a lot of keyboard shortcuts to your environment, you can do this more easily by editing your auto-save settings file directly. You can do this by performing the following:

Bb245788.vs05idetips2(en-US,VS.80).gif

Figure 2. Options dialog - customize Keyboard Shortcuts

Step 1: Export current Keyboard Shortcuts. Go to Tools > Import and Export Settings. . . to start the Import/Export Settings Wizard. Choose "Export selected environment settings" and click Next. Click on "All Settings" to deselect all the checkboxes, and then expand the Options, Environment nodes to select the "Keyboard" checkbox (Figure 3). Click Next to go to the last page of the Wizard. Name the new settings file "MyKeyboardShorcuts.vssettings" and leave the path as the default directory (Figure 4). Click Finish.

Bb245788.vs05idetips3(en-US,VS.80).gif

Figure 3. Select only the Keyboard settings category to export

Bb245788.vs05idetips4(en-US,VS.80).gif

Figure 4. Renaming the settings file to MyKeyboardShortcuts.vssettings

Step 2: Open and edit the settings file. The file is located at My Documents\Visual Studio 2005\Settings\MyKeyboardShortcuts.vssettings. The Visual Studio settings files are just XML files and you can open this with any text editor. I recommend that you open the file with Visual Studio itself, as this will give you syntax coloring and document formatting capabilities. Once you have the file opened, hit "Ctrl+K, Ctrl+D" to have Visual Studio automatically format it. Then, look for the <UserShortcuts> tag. Within this XML element, you can add your own list of shortcuts. An example is shown in Listing 2 below.

...
<UserShortcuts>
   <Shortcut Command="View.CommandWindow" Scope="Global">
Ctrl+W, Ctrl+C
</Shortcut>
   <Shortcut Command="View.SolutionExplorer" Scope="Global">
Ctrl+W, Ctrl+S
</Shortcut>
   <Shortcut Command="View.ErrorList" Scope="Global">
Ctrl+W, Ctrl+E
</Shortcut>
   <Shortcut Command="View.TaskList" Scope="Global">
Ctrl+W, Ctrl+T
</Shortcut>
   <Shortcut Command="View.Output" Scope="Global">
Ctrl+W, Ctrl+O
</Shortcut>
</UserShortcuts>
...

Listing 2. Adding Keyboard Shortcuts directly in the settings file

The XML here is quite easy to understand. You simply have a <Shortcut> element for each of the shortcuts that you want to add. You specify the shortcut itself as this element's content, and you can use modifier keys such as Shift, Ctrl, Alt together by chaining them with the "+" character (for example, Ctrl+Alt+J). You specify the canonical command name of the command that you want to bind the shortcut to in the Command attribute. The Scope attribute will almost always be Global, so we will not discuss that anymore. The most difficult part of this exercise is probably figuring out what the canonical name is for a particular command. The canonical name of a particular command is formed by concatenating the top level menu name with the "." character, and the command name in camel case without any spaces.

After you have added all your shortcuts, save the file.

Step 3: Import the settings file. Now that you have added your shortcuts in your settings file, you can import it back to your environment. Of course, you can also share your settings file with others. Start the Import and Export settings Wizard again, but choose "Import selected environment settings' this time; click Next. Select "No, just import new settings, overwriting my current settings" and click Next. Choose "MyKeyboardShortcuts.vssettings" under the "My Settings" folder and click Next. Have the default selections remain and click Finish.

Showing Shortcuts on ToolTips

You can actually tell the environment to show shortcuts on the ToolTips that are available when you mouse over commands on toolbars. Go to Tools > Customize. . ., and make sure the option Show shortcut keys in ScreenTips is checked.

Bb245788.vs05idetips5(en-US,VS.80).gif

Figure 5. Turning on Show shortcut keys in ToolTips

Window Layout Selector

Visual Studio is a powerful environment with many different tool windows for different tasks and purposes. This is especially true with the new Team System features shipping in VS 2005. We have heard from many customers that it would be useful if there was a way to quickly switch between different window layouts to match their current task at hand. You can actually create this functionality yourself inside VS 2005, but it will involve several steps.

Step 1. Create settings files. Visual Studio 2005 has a new feature that allows you to import/export environment settings. Virtually all customizations that you can make to the environment can be exported to a file so that you can share them with others, import them on a different computer or store it as a backup. The settings that you can import/export include window layout, keyboard shortcuts, menu customizations, fonts & colors and virtually everything in the Options dialog (Tools > Options. . . ). You either export all the environment settings or only a subset of these settings anytime you wish.

In creating our Window Selector, the first step is to create a separate settings file for each of the window layout that you wish to use. In this example, I will create 3 settings file corresponding to the 3 window layouts that I wish to use: CodeWriting, CodeBrowsing, and FormsDesign.

First, simply arrange the window layout the way you prefer when you write code. For me, I prefer to set all the visible tool windows to the auto hide state to maximize coding space. Figure 6 shows how I have arranged the tool windows for this window layout, but feel free to adapt this to your preference. Then, go to Tools > Import and Export Settings to start the Import and Export Settings Wizard. Choose Export selected environment settings and click Next. Select only the window layout checkbox and then click Next. Name the setting CodeWritingWinLayout.vssettings and click Finish. Now you have created the first of three settings files that you need. Repeat the above steps to create the remaining two settings files. Obviously, you need to change the window layout and name the files differently. I have named mine CodeBrowsingWinLayout.vssettings and FormsDesignWinLayout.vssettings.

Click here for larger image

Figure 6. Window layout for coding (click image to enlarge)

Step 2. Create macros to import settings files. Once the settings files have been created, you need to create 3 macros – 1 to import each of the settings file. Listing 3 below shows how trivial this code is.

Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics
Imports System.IO

Public Module Module1

  Public Sub ImportWinLayoutCodeWriting()
    DTE.ExecuteCommand("Tools.ImportandExportSettings",
    "-import:c:\demo\settings\CodeWritingWinLayout.vssettings")
  End Sub

  Public Sub ImportWinLayoutCodeBrowsing()
    DTE.ExecuteCommand("Tools.ImportandExportSettings",
    "-import:c:\demo\settings\CodeBrowsingWinLayout.vssettings")
  End Sub

  Public Sub ImportWinLayoutFormsDesign()
    DTE.ExecuteCommand("Tools.ImportandExportSettings",
    "-import:c:\demo\settings\FormsDesignWinLayout.vssettings")
End Sub

End Module

Listing 3. Macro code for importing a settings file

Step 3. Add buttons to the toolbar. Now it's time to create the actual buttons that will change your window layout. Click on Tools > Customize. . ., click on the Commands tab. Select Macros from the Categories list box, and then scroll down on the list of Commands until you find the three macros that you just wrote. They should be called MyMacros.Module1.ImportWinLayoutCodeWriting, MyMacros.Module1.ImportWinLayoutCodeBrowsing, and MyMacros.Module1.ImportWinLayoutFormsDesign (see Figure 7). Click and drag each of these commands onto the Visual Studio toolbar. You may now want to right-click on the newly placed commands on the toolbar and change the names of these commands to something shorter.

Bb245788.vs05idetips7(en-US,VS.80).gif

Figure 7. Use Customize dialog to place macros onto the toolbar

Close the Customize dialog to save your customizations. You are done with creating your own Window Layout selector. Click on the new buttons on the toolbar and try it out. You can even assign a keyboard shortcut to these commands by going to Tools > Options. . . > Environment > Keyboard page.

Code Snippets

Code snippets are one of the best productivity features introduced in Visual Studio 2005. It allows you to quickly insert fragments of code to avoid tedious typing (such as typing a for loop) or to give you a template of how to accomplish a certain task (such as sending data over the network). Most of the built-in C# snippets are of the first type – they help you in minimizing repetitive typing, while most of the built-in VB snippets are of the second type – they let you code up a specific task more easily.

There are two ways to insert a snippet. You can type the snippet's alias in the code editor and press Tab twice (you only need to press Tab once for VB) to insert the snippet immediately. After the code snippet has been inserted, you can press Tab and Shift+Tab to jump to different fields within the snippet. This allows you to quickly change the parts of code that need to be modified. Notice that in C#, code snippet aliases also have IntelliSense. You can tell that an item is a code snippet in the IntelliSense list by its snippet icon.

Bb245788.vs05idetips8(en-US,VS.80).gif

Figure 8. IntelliSense fully supports code snippets

If you don't remember your code snippet's alias, you can also insert it by pressing "Ctrl+K, Ctrl+X" within the code editor or do a mouse right-click with the mouse and select Insert Snippet.... This shows the code snippet picker, which enables you to browse all the snippets that are applicable to your current programming language and to choose the one you want to insert. This method of inserting code snippets works for both C# and Visual Basic. Visual Basic users have yet another way to insert snippets: you can type the first few letters of a snippet alias, followed by "?" and pressing Tab. Visual Studio will display an alphabetical listing of all the code snippet aliases with the one most closely matched highlighted. This feature is available only for Visual Basic users.

Click here for larger image

Figure 9. Inserting a code snippet in C# (click image to enlarge)

Personally, the most exciting part of the code snippet feature is that you can create your own snippets for your personal use or share them with the community. Of course, you can also download code snippets that other developers have created.

It is very easy to create your own code snippet right inside Visual Studio. I will show you how you can do this via an example. I frequently write quick-and-dirty utilities to help me do my work. Many of these utilities have a common patter: open a file, do some processing, and then close the file. Here is how I would create my snippet.

Step 1: Create the XML file. Each code snippet is contained within an XML file. Inside Visual Studio, simply go to File > New. . . > File. . ., and then choose the XML File type.

Bb245788.vs05idetips10(en-US,VS.80).gif

Figure 10. Creating a new XML file

Step 2: Define the snippet. Interestingly enough, there is even a snippet to create a snippet. Simply press Ctrl+K, Ctrl+X on the second line of the file and choose the Snippet code snippet, the template of a code snippet file is automatically inserted for you.

Click here for larger image

Figure 11. Using XML snippet to create other snippets (click image to enlarge)

The title, author, shortcut, and description fields are pretty self-explanatory and I will not go into detail with those. The contents within the <Snippet> tags deserve some discussion and can be best explained by my example below.

Essentially, you put all your code inside the <![CDATA[...]]> tag, which is inside the </Code> tag. For fields that you want the user to be able to easily replace, you put a pair of "$" characters around them. In my example, I have three literals that I want users of my snippet to easily replace: StrmReader, FilePath, and Line. These three literals are used within the CDATA section with a pair of "$" characters surrounding them. In addition, each of these literals must be defined within the <Declarations> element. Each is given an ID and an optional default value.

The astute reader will notice that there is also another literal inside my code snippet that I did not define: $end$. This is a special literal that specifies where the cursor will be located when the user presses Enter after they have completed filling in the snippet fields. There is also another special literal that I am not showing here: $selected$. The $selected$ literal is meaningful only for code snippets that are of the SurroundsWith type. It defines where the selected code segment will be placed when this snippet is inserted by using Surround With...

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippet Format="1.0.0" xmlns="https://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <Header>
    <Title>File Processing</Title>
    <Author>James Lau</Author>
    <Shortcut>fp</Shortcut>
    <Description>Opens a file, does some processing, and then closes the file.</Description>
    <SnippetTypes>
      <SnippetType>SurroundsWith</SnippetType>
      <SnippetType>Expansion</SnippetType>
    </SnippetTypes>
  </Header>
  <Snippet>
    <Declarations>
      <Literal>
        <ID>StrmReader</ID>
        <Default>strmReader</Default>
      </Literal>
      <Literal>
        <ID>FilePath</ID>
        <Default>fPath</Default>
      </Literal>
      <Literal>
        <ID>Line</ID>
        <Default>strLine</Default>
      </Literal>
    </Declarations>
    <Code Language="CSharp">
      <![CDATA[         
   StreamReader $StrmReader$ = null;
   try
   {
      $StrmReader$ = new StreamReader($FilePath$);
      string $Line$;
      while (($Line$ = $StrmReader$.ReadLine()) != null)
      {
         // Perform some processing
         $selected$
         $end$
      }
   }
   catch (IOException ioex)
   {
      // Handle exception
   }
   finally
   {
      $StrmReader$.Close();
   }
    ]]>
    </Code>
  </Snippet>
</CodeSnippet>

Listing 4. Sample code snippet content

Customizing Visual Studio Start Page

The new Start Page in Visual Studio 2005 not only contains a live RSS feed that provides up-to-date information on MSDN news. If you prefer to read some other RSS feed on the Start Page, you can customize the RSS news channel by selecting Tools, then selecting Options. . ., selecting Environment, and then choosing Startup page, where you can edit the URL under Start Page news channel. If you prefer to not have the Start Page automatically be displayed each time you launch Visual Studio, you can also change this behavior by choosing Show empty environment under At startup on the same options page.

Team Settings

Another new but less known feature in Visual Studio 2005 is Team Settings. If you work in a team environment (and most of us do), then Team Settings may be able to help you in enforcing team coding rules or in setting up Visual Studio more quickly.

Let's assume that you would like to enforce a basic set of code formatting rules within your team. Instead of specifying what these rules are and have each team member customize the IDE options to comply with those rules, you can simply create a settings file and have your team members point to it. Whenever the team settings file is updated, it will automatically be imported over the user's existing settings the next time he or she starts Visual Studio. Here is what you do to leverage the power of this feature.

Step 1: Create settings file. You can use Team Settings to enforce any IDE customizations you like. The most common settings we expect developers to use Team Settings for are the code formatting settings. But you can use this feature for any Visual Studio settings that can be exported, such as Fonts & Colors, SourceSafe settings, keyboard shortcuts, menu customizations, etc. Simply customize the desired settings within Visual Studio, and then use Tools > Import/Export Settings. . . to export them to a known location. It is important that you only export the set of settings that you would like to share with your team.

Step 2: Place settings file in UNC path. Copy the settings file you exported from Step 1 to a network path that your team members have access to. On my machine, I have shared my team settings file at \\jameslau\public\teamsettings.settings.

Step 3: Change Team Settings path. Have your team members change their Team Settings path to point to your team settings file. They can do this by going to Tools > Options. . . > Environment > Import and Export Settings. Select (check) the Use team settings file check box and specify the path of the team settings file.

Bb245788.vs05idetips12(en-US,VS.80).gif

Figure 12. Options dialog for changing Team Settings path

/resetuserdata Switch

The last tip that I will share with you concerns the /resetuserdata switch. You can use this switch to reset Visual Studio to its out-of-box state if Visual Studio ever runs into a damaged state that you cannot recover from. Examples of these problems may be a corrupted window layout file, corrupted menu customization file, or corrupted keyboard shortcuts file. Disclaimer: you will lose all your environment settings and customizations if you use this switch. It is for this reason that this switch is not officially supported and Microsoft does not advertise this switch to the public (you won't see this switch if you type devenv.exe /? in the command prompt). You should only use this switch as the last resort if you are experiencing an environment problem, and make sure you back up your environment settings by exporting them before using this switch.

To use this switch, do the following:

  1. Shut down all instances of Visual Studio 2005.
  2. Click Start, the choose Run....
  3. Type "devenv.exe /resetuserdata".

This command will take a couple of minutes to run as Visual Studio cleans up and sets itself back to its original state. You may open Task Manager at this point to check whether the devenv.exe process is still running. After it has completed running, you can restart Visual Studio. You will then be greeted by the first launch dialog again, as if you are running Visual Studio for the first time on your machine.

Conclusion

We are working hard to continue to bring you useful productivity features in Visual Studio. I hope these tips are useful to you and can help you in becoming a Visual Studio power user. If you have comments, feedback, or suggestions for Visual Studio IDE issues, I would love to hear from you. You can write me at jameslau@microsoft.com.

© Microsoft Corporation. All rights reserved.