How to create image dimension macros in Visual Studio?

I hate to do repetitive tasks. When I am writing CSS very often I need to set a background image to some container. But I never know image dimensions. So usually I am going to explorer or PhotoShop to find image dimensions and then manually type CSS width and height for it. Lucky me Visual Studio has macros. Here is a simple guide on how to create a context menu “Paste Image CSS” command.

  1. Launch Macros IDE
  2. In the Macros IDE, you should see a default Macro project “MyMacros”. Add a new Module to the MyMacros project by right-clicking on the project and then choosing Add | Add Module.
  3. Now copy and paste a macro code provided below.
  4. Now here is a little trick. From the Visual Studio IDE, Choose Tools | Customize. In the Customize window, check the “Context Menus” from the Toolbars area. If you have done it correctly, you should see a new toolbar at the top which has most of the Contextual Menus you see while working in the VS IDE. In Project and Solution Context Menu find an Item submenu. While an Item submenu is open, go to the Commands tab of the Customize Window and click the Macros. Now find and drag your Macro (PasteImageCSS) and drop it over the desired point in the Context Menu.

Insert Image CSS Macros Demo

Sub PasteImageCSS()
    Dim win As Window = DTE.Windows.Item(Constants.vsWindowKindSolutionExplorer)
    Dim solution As UIHierarchy = win.Object
    Dim file As ProjectItem = solution.SelectedItems(0).Object
    Dim editPoint As EditPoint = DTE.ActiveDocument.Selection.ActivePoint.CreateEditPoint

        Dim objImage As System.Drawing.Image = System.Drawing.Image.FromFile(file.FileNames(0))
        editPoint.Insert(String.Format( \_
        "background-image:url(images/{2});{0}" & \_
        "{1}background-repeat:no-repeat;{0}" & \_
        "{1}width:{3}px;{0}" & \_
        "{1}height:{4}px;{0}" & \_
        "{1}display:block;" \_
        , ControlChars.NewLine, ControlChars.Tab, file.Name, objImage.Width, objImage.Height))
    Catch ex As Exception
        MsgBox("Selected file is not an image.")
    End Try

End Sub
Posted on July 30, 2009 by