January 16, 2012

Visual Studio 2008 Macros

I recently tried Macros in Visual Studio 2008. You can do various customization to the IDE using the Macro editor. For an example:

  • Google the selected word.
  • Display a message box after a build is completed.
  • Record an operation and play it.
  • Etc...
As an example I will be covering first two from the above.

To create Macros, go to Tools menu select Macros and then select Macros IDE. This will open up a new program (Microsoft Visual Studio Macros) and using the editor you can add macros in to the IDE.


If you haven’t used the Macro IDE before, the first thing you’ll notice is that it resembles the regular VS.NET IDE, except the Macro IDE is used solely for the creation, editing, and compiling of macros that can be used within your Visual Studio IDE.


Open up the MyMacros project and see if it already contains an EnvironmentEvents module. 

Add the following code snippet by adding a new VB code file.

    Private Const BROWSER_PATH As String = "C:\Program Files (x86)\Mozilla Firefox\firefox.exe"

    Sub SearchGoogle()
        Dim cmd As String
        cmd = String.Format("{0} http://www.google.com/search?hl-en&q={1}", BROWSER_PATH, DTE.ActiveDocument.Selection.Text)
        Shell(cmd, AppWinStyle.NormalFocus)
    End Sub


This will spawn a new Firefox Window and send the selected text to Google.


You can access Visual Studio environment (EnvDTE) instance in a Macro to do various things such as customize pre-build event or a post-build event. EnvDTE is an assembly-wrapped COM library containing the objects and members for Visual Studio core automation.


For an example the following code displays an message box after a build is completed. For this you hook into the OnBuildDone event the same way you did for the project build complete.



    Private Sub BuildEvents_OnBuildDone(ByVal Scope As EnvDTE.vsBuildScope, ByVal Action As EnvDTE.vsBuildAction) Handles BuildEvents.OnBuildDone
        'Alert that we finished building!
        If DTE.MainWindow.WindowState = EnvDTE.vsWindowState.vsWindowStateMinimize Or DTE.MainWindow.Visible = False Then
            System.Windows.Forms.MessageBox.Show("Build is complete!", _
                IO.Path.GetFileNameWithoutExtension(DTE.Solution.FullName), _
                MessageBoxButtons.OK, _
                MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, _
                MessageBoxOptions.DefaultDesktopOnly)
        End If
    End Sub


These are some pretty simple examples, but you have the power of the .NET Framework in your hands for any of these events so you are limited only by what you can come up with to handle.


The post build event will automatically run after a build if the IDE is invisible or minimized. However to run the Google macro, you can assign this Macro to a toolbar by going into Tools, Customize, Command, Macros and drag and dropping SearchGoogle function.




No comments: