[tip]Quick toggle between .h and .cpp files

Quick toggle between .h and .cpp files

When programming C++ it is a very common need to switch between the .h and .cpp file. There are no built in way to do this in Visual Studio, however it is possible to accomplish! You can either use an expensive helper program, such as Visual Assist or you can do it freely by writing a macro.

To write a macro that switch between the source and header file is easy, here is a step-by-step guide for Visual Studio 2005.

Creating the macro

  1. Start Visual Studio 2005
  2. Go into ‘Tools->Macros->Macros IDE‘
  3. Right click on ‘My Macros’ and select ‘Add->Add New Item’
  4. Select ‘Module’ and name it ‘ToggleCPPH’ and click on ‘Add’
  5. Select the newly created module and paste this into it
  6. Public Module ToggleCPPH    Sub Toggle() 

      Dim fileName As String = DTE.ActiveDocument.Name

    If (fileName.EndsWith(".cpp")) Then

      fileName = fileName.Remove(fileName.IndexOf(".")) + ".h"

      Else

      fileName = fileName.Remove(fileName.IndexOf(".")) + ".cpp"

      End If

    DTE.ExecuteCommand("File.OpenFile", DTE.ActiveDocument.Path + fileName)

      End Sub

    End Module
  7. Save the macro and switch back to the Visual Studio 2005 IDE.

Assigning the toggle macro to a shortcut key

  1. Click on ‘Tools->Options’ and select ‘Keyboard’.
  2. Select your C++ keyboard mapping scheme and type ‘macro’ in the ‘Show commands containing:’ field. Note, if you can’t see the macro in the list, try to restart Visual Studio.
  3. Select the ToggleCPPH macro and assign in the some convincing shortcut keys.
  4. Click on ‘Assign’.
  5. Click on ‘Ok’.

Testing the toggle macro

  1. Open an .h or .cpp file in Visual Studio.
  2. Press the shortcut keys and snap – you are now hopefully in the corresponding header or source file!

Notes

This is a very simple macro, no error handling has been implemented. If no corresponding .h or .cpp file exists a message box will show up and say no such file exists – in many cases this is good enough. If you are using a lot of other files (e.g. .inl) you may want to add that into the toggle chain. I am not sure how to do this, you will have to check if it exists before trying to open it. I will leave this as an exercise to you. If you find a solution, please don’t hesitate to post it in the comments below!

Keep the coding up!

原文地址:https://www.cnblogs.com/taoxu0903/p/1775906.html