Hidden Features of Visual Studio (2005-2010)?

Viewed 30589

Visual Studio is such a massively big product that even after years of working with it I sometimes stumble upon a new/better way to do things or things I didn't even know were possible.

For instance-

  • Crtl + R, Ctrl + W to show white spaces. Essential for editing Python build scripts.

  • Under "HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0\Text Editor" Create a String called Guides with the value "RGB(255,0,0), 80" to have a red line at column 80 in the text editor.

What other hidden features have you stumbled upon?

100 Answers

Make a selection with ALT pressed - selects a square of text instead of whole lines.

Tracepoints!

Put a breakpoint on a line of code. Bring up the Breakpoints Window and right click on the new breakpoint. Select 'When Hit...'. By ticking the 'Print a message' check box Visual Studio will print out a message to the Debug Output every time the line of code is executed, rather than (or as well as) breaking on it. You can also get it to execute a macro as it passes the line.

You can drag code to the ToolBox. Try it!

Click an identifier (class name, variable, etc) then hit F12 for "Go To Definition". I'm always amazed how many people I watch code use the slower right-click -> "Go To Definition" method.

EDIT: Then you can use Ctrl+- to jump back to where you were.

CTRL+SHIFT+V will cycle through your clipboard, Visual Studio keeps a history of copies.

CTRL-K, CTRL-D

Reformat Document!
This is under the VB keybindings, not sure about C#

How many times do you debug an array in a quickwatch or a watch window and only have visual studio show you the first element? Add ",N" to the end of the definition to make studio show you the next N items as well. IE "this->m_myArray" becomes "this->m_array,5".

Incremental search: While having a source document open hit (CTRL + I) and type the word you are searching for you can hit (CTRL + I) again to see words matching your input.

You can use the following codes in the watch window.

@err - display last error
@err,hr - display last error as an HRESULT
@exception - display current exception
  • Ctrl-K, Ctrl-C to comment a block of text with // at the start
  • Ctrl-K, Ctrl-U to uncomment a block of text with // at the start

Can't live without it! :)

Stopping the debugger from stepping into trivial functions.

When you’re stepping through code in the debugger, you can spend a lot of time stepping in and out of functions you’re not particularly interested in, with names such as GetID(), or std::vector<>(), to pick a C++ example. You can use the registry to make the debugger ignore these.

For Visual Studio 2005, you have to go to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio \8.0\NativeDE\StepOver and add string values containing regular expressions for each function or set of functions you wish to exclude; e.g.

std::vector.*::.*
TextBox::GetID

You can also override these for individual exceptions. For instance, suppose you did want to step into the vector class’s destructor:

std::vector.*::\~.*=StepInto

You can find details for other versions of Visual Studio at http://blogs.msdn.com/andypennell/archive/2004/02/06/69004.aspx

Ctrl-F10: run to cursor during debugging. Took me ages to find this, and I use it all the time;

Ctrl-E, Ctrl-D: apply standard formatting (which you can define).

TAB key feature.

  1. If you know snippet key name, write and click double Tab. for example: Write

    foreach

and then click tab key twice to

foreach (object var in collection_to_loop)
{

}

2. If you write any event, write here

        Button btn = new Button();
        btn.Click +=         

and then click tab key twice to

private void Form1_Load(object sender, EventArgs e)
{
        Button btn = new Button();
        btn.Click += new EventHandler(btn_Click);     
}    
void btn_Click(object sender, EventArgs e)
{
        throw new Exception("The method or operation is not implemented.");
}

btn_Click function write automatically

  1. in XAML Editor, Write any event. for example:

MouseLeftButtonDown then click tab
MouseLeftButtonDown="" then click tab again MouseLeftButtonDown="Button_MouseLeftButtonDown" in the code section Button_MouseLeftButtonDown method created.

Sara Ford has this market cornered.

http://blogs.msdn.com/saraford/default.aspx

More Visual Studio tips and tricks than you can shake a stick at.

Some others:

  • The Visual Studio 2005 and 2008 3-month trial editions are fully-functional, and can be used indefinitely (forever) by setting the system clock back prior to opening VS. Then, when VS is opened, set the system clock forward again so your datetimes aren't screwed up.
  • But that's really piracy and I can't recommend it, especially when anybody with a .edu address can get a fully-functional Pro version of VS2008 through Microsoft Dreamspark.
  • You can use Visual Studio to open 3rd-party executables, and browse embedded resources (dialogs, string tables, images, etc) stored within.
  • Debugging visualizers are not exactly a "hidden" feature but they are somewhat neglected, and super-useful, since in addition to using the provided visualizers you can roll your own for specific data sets.
  • Debugger's "Set Instruction Pointer" or "Set Next Statement" command.
  • Conditional breakpoints (as KiwiBastard noted).
  • You can use Quickwatch etc. to evaluate not only the value of a variable, but runtime expressions around that variable.

Custom IntelliSense dropdown height, for example displaying 50 items instead of the default which is IMO ridiculously small (8).

(To do that, just resize the dropdown next time you see it, and Visual Studio will remember the size you selected next time it opens a dropdown.)

Discovered today:

Ctrl + .

Brings up the context menu for refactoring (then one that's accessible via the underlined last letter of a class/method/property you've just renamed - mouse over for menu or "Ctrl" + ".")

A lot of people don't know or use the debugger to it's fullest - I.E. just use it to stop code, but right click on the red circle and there are a lot more options such as break on condition, run code on break.

Also you can change variable values at runtime using the debugger which is a great feature - saves rerunning code to fix a silly logic error etc.

Line transpose, Shift-Alt-T
Swaps two line (current and next) and moves cursor to the next line. I'm lovin it. I've even written a macro which changed again position by one line, executed line transpose and changed line position again so it all looking like I swapping current line with previous (Reverse line transpose).

Word transpose, Shift-Ctrl-T

When developing C++, Ctrl-F7 compiles the current file only.

To auto-sync current file with Solution Explorer. So don't have to look where the file lives in the project structure

Tools -> Options -> Projects and Solutions -> "Track Active Item in Solution Explorer"

Edit: If this gets too annoying for you then you can use Dan Vanderboom's macro to invoke this feature on demand through a keystroke.

(Note: Taken from the comment below by Jerry).

Document Outline in the FormsDesigner (CTRL + ALT + T)

Fast control renaming, ordering and more!

I'm not sure if it's "hidden", but not many people know about it -- pseudoregisters. Comes very handy when debugging, I've @ERR, hr in my watch window all the time.

Ctrl-Minus, Ctrl-Plus, navigates back and forward where you've been recently (only open files, though).

CTRL + Shift + U -> Uppercase highlighted section. CTRL + U -> Lowercase the highlighted section Great for getting my SQL Statements looking just right when putting them into string queries.

Also useful for code you've found online where EVERYTHING IS IN CAPS.

To display any chunk of data as an n-byte "array", use the following syntax in Visual Studio's QuickWatch window:

variable, n

For example, to view a variable named foo as a 256-byte array, enter the following expression in the QuickWatch window:

foo, 256

This is particularly useful when viewing strings that aren't null-terminated or data that's only accessible via a pointer. You can use Visual Studio's Memory window to achieve a similar result, but using the QuickWatch window is often more convenient for a quick check.

CTRL-D then type ">of " then file name. If the standard toolbar is up crtl-d put you in find combobox and there is now a dropdown with files in your solution that match the start of the filename you typed. Pick one and it will open it. This alternative to the open filedialog is awesome for big solutions with lots of directories.

Drag-drop text selections to the Watch window while in the debugger.

.NET debugger allows you to give objects identifiers, and to refer them via those identifiers later during the session. To do so, you right-click on the variable (or expression) referencing the object in Autos/Locals/Watch window, or in the tooltip, and select "Create Object ID". IDs are sequential integer numbers, starting from 1, and suffixed by "#" - e.g 1# will be the first ID you create.

After the ID is created, if the object is associated with a given ID, it is displayed in parentheses.

You can use 1# to reference the object by ID anywhere you can normally use expressions - in Watch window, in condition of a conditional breakpoint, and so on. It's most handy when you want to set a breakpoint on a method of some particular object only - if you can first track the object creation, or some other place where this particular object is referenced, you just create the ID for it, and then set a new breakpoint with condition such as this==1#.

  • The memory windows, very useful if you're doing low level stuff.
  • Control + K , Control + F - Format selection - great for quickly making code neat
  • Regions, some love them, some hate them, most don't even know they exist
  • Changing variables in debug windows during execution
  • Tracepoints
  • Conditional break points
  • Hold down Alt and drag for 'rectangular' selection.
  • Control+B for a breakpoint, to break at function
  • Control+I for incremental search, F3 to iterate

Press the F8 key to cycle through search results. (Shift+F8 for reverse direction)

Hit F12 to go to definition of variable.

Shift + alt + arrow keys = Block select!

  • Ctrl-K, Ctrl-C to comment a block of text with // at the start
  • Ctrl-K, Ctrl-U to uncomment a block of text with // at the start

Can't live without it! :)

Shift+Alt+F10 brings up the built in refactoring menu. Great for adding method stubs from interfaces, and adding Using statements automatically for specific classes.

There is an article about this. It seems to be a lengthy collection.

You can drag down the little gray box above the vertical scrollbar to split the window into two views of the same file, which can be scrolled independently - great if you're comparing two parts of the same file.

View, Other Windows, Object Test Bench

The object test bench can be used to execute code at design-time.

You can right-click on a type in Class View, click Create Instance, and select a constructor. You can then supply values for its parameters, if any, and the instance will show up in the Object Test Bench.

You can also call static methods by right-clicking a type and clicking Invoke Static Method.

In the Object Test Bench, you can right-click on an object to call methods, and you can hover over it and see its structure (like you can when debugging). You can also assign to and interact with these variables in the Immediate window, also at design time.

This feature can be useful when writing a library. Please note that to use this, your solution must be compile first.

Pseudovariables in the debugger: http://msdn.microsoft.com/en-us/library/ms164891.aspx

$exception: avoids the need to give your exceptions names (and cause variable not referenced warnings).

$user: tells you which user is running the application...sometimes useful when trying to diagnose permission issues.

The most important feature I can't live without is Visual Studio 2008. :P

The Debugger :-) Beats Notepad by miles.

I always map control + alt + f4 to documents.CloseAllWindows in options>environment>keyboard.

Is somewhat more intuitive than using the mouse.

I think the ability to right click on a Stored Procedure in Server Explorer and debug..

Copy-paste from a Watch window of an object's expanded properties in the debugger into Excel will perserve the tabular format and persist the data after the debug session is over.

Here is the Macro source for my aspx/aspx.cs flipper. It works in 2005, but it may have issues in 08.. I'm not sure... This was taken from my other cpp/h flipper, so there might be some clean up needed to make it the best it could be. I'm not paid to write Macros, so I have to blast though them as quickly as possible when I need one.

    Sub OpenASPOrCS()
    'DESCRIPTION: Open .aspx file if in .cs file, open .cs file if in .aspx file
    On Error Resume Next

    ' Get current doc path
    Dim FullName
    FullName = LCase(ActiveDocument.FullName)
    If FullName = "" Then
        MsgBox("Error, not a .cs or asp file!")
        Exit Sub
    End If

    ' Get current doc name
    Dim DocName
    DocName = ActiveDocument.Name

    Dim IsCSFile
    IsCSFile = False
    Dim fn
    Dim dn
    If (Right(FullName, 3) = ".cs") Then
        fn = Left(FullName, Len(FullName) - 3)
        dn = Left(DocName, Len(DocName) - 3)
        IsCSFile = True
    ElseIf ((Right(FullName, 5) = ".aspx") Or (Right(FullName, 5) = ".ascx")) Then
        fn = FullName + ".cs"
        dn = DocName + ".cs"
    Else
        MsgBox("Error, not a .cs, or an asp file!")
        Exit Sub
    End If

    Dim doc As EnvDTE.Documents

    DTE.ItemOperations.OpenFile(fn)
    doc.DTE.ItemOperations.OpenFile(fn)

    If Err.Number = 0 Then
        Exit Sub
    End If

    ' First check to see if the file is already open and activate it
    For Each doc In DTE.Documents()
        If doc.Name = dn Then
            doc.Active = True
            Exit Sub
        End If
    Next

End Sub

Ctrl+L deletes the current selected line. This is an awesome time saver (if used responsibly of course!!!)

Ctrl-M + Ctrl-L Toggle Collapse All - Expand All

Ctrl-T swaps the last two letters. For example, "swithc" -> "switch".

Ctrl+Shift+L deletes the current line (without cutting it to the clipboard)

View, Code Definition Window.

The Code Definition Window shows the definition of the currently selected identifier (If it's in your solution, it'll show your sourced; otherwise, it'll extract metadata, like right-click, Go To Definition)

One that I only just discovered. When dealing with COM it's possible to lookup a brief message from the cryptic hexadecimal error number using a tool called errlook.exe.

The useful tool is located in your VS\Common7\Tools directory.

Not exactly a hidden feature, but one thing I've done is add a "Start Without Debugging" button next to my "Start With Debugging" button. Just click the down arrow at the right end of the toolbar. Then select "Add or Remove buttons". Then Customize. In the commands tab select the Debug category. Find the Start Without Debugging command and drag it to where you want it on the toolbar.

My best feature is one I had to make myself.. It's a cpp/h flipper. If you are looking at the .h file, and hit this macro, (or its keyboard shortcut), it will open the cpp file, and vice-versa.

I can provide the source if anyone wants it.

Enable Intellisense in Skin Files

  1. Go to Tools->Options menu.
  2. Pick Text Editor -> File Extesion fom a tree at the left part of Options dialog.
  3. Type skin in Extesion text box.
  4. Select User Control Editor from Editor dropdown.
  5. Click Add and then Ok to close dialog and re-open your skin files.

The Open button in the File Open dialog has a little down arrrow next to it. Click that and you get the "Open With" option which includes the Binary Editor. As a systems-type guy, I find it quite valuable, but most of my colleagues hadn't known about it until I showed them.

Re: Stopping the debugger from stepping into trivial functions.

In C#, you can also add an attribute [DebuggerStepThrough] (using System.Diagnostics) to a method. This causes the debugger to, ironically, not step through the method.

CTRL-G for jumping to a specific line number. Saves a few seconds when you've got a line number in a large code file.

I wanted to talk about comment (Ctrl + k, Ctrl + c) and uncomment (Ctrl + k, Ctrl + u) shortcuts but a Bratt (:p) already mentioned them.

How about the Ctrl + k, Ctrl + d shortcut, very convenient to format markup (ASP.NET, HTML) and JavaScript code!

I don't know how unknown most people consider them to be, but I don't think that a lot of people use snippets.

I discovered them a while back and then found that they were customizable by editing the xml in the Visual Studio Program Files directory. They make it super easy to add a lot of code quickly.

Also, to save time when using snippets make sure you hit tab twice and not try to do everything through the right click menu.

In addition to all others said like:

  • Ctrl + K + D
  • Ctrl + K + U
  • Ctrl + M + L
  • Ctrl + M + O

Selecting when you hold "Alt".
Hiting F12 on the instead of right click and choose "Go To Definition".

  • Ctrl + K + C for comment.
  • Ctrl + K + U for uncommenting.

Today if found something new:
In WebFroms in Design mode, go to Tools menu and choose "Generate Local Resources". It's really handy for making multilingual web applications.

How about Ctrl + C to copy the current line to the clipboard without doing any range selection. This is sooooo... simple and useful.

  • Print the shortcuts from http://www.microsoft.com/downloads/details.aspx?FamilyID=6bb41456-9378-4746-b502-b4c5f7182203&DisplayLang=en">the Microsoft page and put them next to you. Try to learn a new one every day. You'll find all shortcuts already mentioned here + lots more. Some very useful contain formatting a code block, commenting, navigate between pages,...
  • Get Resharper, it's a plugin which whill greatly increase your efficiency. If you use Resharper, you can find a list with shortcuts.
  • I updated my code flipper, I posted earlier. I added support for ASP Controls.

    Larry

    Just found out back and forward buttons on my mouse moves back or forward one document.

    Think I was wrong about this one. Only happens when searched for stuff.

    Task List Tokens

    Configured task list tokens are retrieved later while opening task list window and select user comments option, this will display all user comments that contains configured tokens.

    This will be so useful if you try to retrieve TODO comments for example.

    To use it; Tools --> Options --> Environment --> Task List, add required tokens.

    Visual Assist, in general, while a bit OT for this question, is a great app and really helps with the day-to-day running of visual studio. Their open-any-file and find-any-symbol windows are particularly awesome.

    Related