My current assignment at work has me working through a lot of old code. Code that now needs to be modified to implement new features and remove bugs. While updating or modifying existing code it is very important to insert comments stating why the modifications were carried out and the date on which they were carried out. Eventually when other developers work on the same piece of software and compare revisions, they shouldn’t be left wondering why a certain modification was made.
Unfortunately, Visual Studio lacks insert date time at current position functionality. But what it does support are Macros, and using those, it’s quite easy to implement that feature ourselves.
Macros are written in VB.NET. The following VB.NET code can be used to insert the date time at the current caret position -
Sub PrintDateTime() If (Not IsNothing(DTE.ActiveDocument)) Then Dim selection As TextSelection = DTE.ActiveDocument.Selection selection.Insert(DateTime.Now.ToString()) EndIf EndSub
The code above creates a module called
- It first checks if there is an active document, if there, it gets the currently selected text.
- It then inserts current date time at the currently selected caret location.
Next step is to place this code in the correct place.
- Open up the Macro explorer by pressing ALT + F8.
- In the Macro explorer right click on Macros, and click on ‘New Macro Project’.
- Give it a name, and once it’s created, it should be visible in the Macro explorer.
- Create a new Module under the project and give it a name that relates to what you are doing
- Double click on the new Module to open a Macro editor.
- Paste the code above in that editor and save the file.
Now that that is done, your Module should be visible under your project. The next thing we have to do is to assign our newly created Macro to a shortcut key, so that we can easily run it whenever we want.
- On the file menu, click on Tools > Options
- On the window that opens up, in the tree view, go to Environment > Keyboard
- In the Show commands containing textbox, type the name of the Module you created earlier and it should show up in the list below the textbox. Select it.
- In the Press shortcut keys textbox, press the combination of keys that you want to use whenever you wish to run your Macro.
- Make sure Global is selected under Use new shortcut in: and then press the Assign button, followed by OK.
It’s time to see if what we did works! Open up a document and press the same combination of keys that you used to create the shortcut. Once you do, the date time should be inserted at your current caret position and this should work for any document that you create inside Visual Studio 2010.