Saturday, September 22, 2007

The one thing that I always miss in Visual Studio is a quick way to open a file that is part of a solution. By "quick" I mean not requiring a mouse action and with minimal amount of typing. It came out that it is indeed possible to do so without any addon's. As Robert Prouse shows in his blog entry on Quickly Find/Open a File in Visual Studio, we can do so by using the Find drop down (usually it can be found on a toolbar). You get there by pressing Ctrl + d or Ctrl + /. Also in the comments to his post, there is a hint, that we can use a Ctrl + Alt + a to open a command window where you can issue commands like "open [filename]". Cool things indeed. But there is more to it!

I decided to play a bit with Visual Studio Macros and see what I can come up with.

The first thing was writing a macro for opening a file. Functionality similar to the above mentioned, but implemented using macros (later I will write why I decided to reinvent the wheel). As it came out, the documentation on the subject is not very good. It hardly exists! So I had to experiment a bit and after a while I had it working.

To make a Macro step by step:

  1. Run Visual Studio
  2. Press Alt + F11 (or go to Tools->Macros->Macro IDE... menu item)
  3. Under MyMacros, add a new Module.

In the newly added module, start writing code. It is VB.NET so it may cause a little discomfort for a C# developer, but it shouldn't be a major problem.

My procedure for opening files looks as follows:

Sub OpenFile()
    Dim fileName As String = InputBox("Open file:")
    If String.IsNullOrEmpty(fileName) Then
        Return
    End If
    Dim item As EnvDTE.ProjectItem = DTE.Solution.FindProjectItem(fileName)
    If item Is Nothing Then
        MsgBox("File not found", MsgBoxStyle.Exclamation)
        Return
    End If
    item.Open()
    item.Document.Activate()
End Sub

When the code is ready, save it and return to the main instance of Visual Studio and set up a shortcut key.

Setting up a shortcut is easy:

  1. Go to Tools->Options->Environment->Keyboard
  2. Find your macro
  3. Set up a shortcut key (such as Ctrl + o, Ctrl + f) and press assign

From now on, you can use the macro.

The drawback of using this method for opening files is that it does not provide intellisense support, but we can do more with macros than just opening files... Just read my next post.

kick it on DotNetKicks.com