Click here to Skip to main content
13,349,032 members (69,128 online)
Click here to Skip to main content
Add your own
alternative version

Stats

131.3K views
979 downloads
23 bookmarked
Posted 30 Apr 2002

Switch between Header and CPP File for Visual Studio .NET

Rate this:
Please Sign up or sign in to vote.
Here are two methods that allow you to quickly switch between associated header and implementation files in Visual Studio .NET

Introduction

Here are two methods that allow you to quickly switch between the associated header and implementation files in Visual Studio .NET.

Pavel Sokolov's Solution

A simple macro that allows you to quickly switch between the associated header and implementation files. This is a modification for Visual Studio .NET of the macro by Nooruddin Kapasi.

This macro simply switches between a *.h file and a *.cpp file, without any errors (if the *.h or the *.cpp file does not exist).

The Code

Option Strict Off
Option Explicit Off

Imports EnvDTE
Imports Microsoft.VisualBasic

Public Module Switch

    Sub Switch()
        '////////////////////////////////////////////
        'Nooruddin Kapasi 1998.
        'Pavel Sokolov , CEZEO software , http://www.cezeo.com , Adaptation for .NET
        'DESCRIPTION: Switch Between Header and cpp
        '////////////////////////////////////////////

        Dim a As String
        Dim b As String
        Dim Flag As Integer
        Flag = 0
        a = DTE.ActiveDocument.FullName()
        tmp = InStr(a, ".cpp")
        If tmp Then
            b = Left(a, Len(a) - 3) + "h"
            Flag = 1
        Else
            tmp = InStr(a, ".h")
            If tmp Then
                b = Left(a, Len(a) - 1) + "cpp"
                Flag = 1
            End If
        End If

        If Flag Then
            DTE.Documents.Open(b, "Text")
        End If
    End Sub

End Module

Pierre Arnaud's Solution

The Switch_H_CPP macro switches between the active document (either source file or header file) and its counterpart (either header file or source file). Whereas simpler macros get this job done more efficiently (see the above), they do not work if the header files and source files are not stored in the same directory.

Switch_H_CPP looks for a matching counterpart by walking through all the loaded project files. It can, therefore, deduce the full path of the file and open it even if it is in a different directory as the active document.

Source

Here comes the source:

Option Strict Off
Option Explicit Off

Imports EnvDTE
Imports System.Diagnostics

Public Module Opac

    Function WalkProjectItemsAndOpen(ByRef items As ProjectItems, _
                                     ByRef name As String) As Boolean
        Dim item As ProjectItem

        If ReferenceEquals(items, Nothing) Then
            Return False
        End If

        For Each item In items
            Dim sub_items As ProjectItems
            sub_items = item.SubProject
            If Not sub_items Is Nothing Then
                If WalkProjectItemsAndOpen(sub_items, name) Then
                    Return True
                End If
            End If
            If item.Name = name Then
                'MsgBox("Found " + name + " in project " + _
                                   items.ContainingProject.UniqueName)
                Dim op As ItemOperations
                op = DTE.ItemOperations
                op.OpenFile(item.FileNames(0), Constants.vsViewKindTextView)
                Return True
            End If
        Next
        Return False
    End Function

    Sub Swap_H_CPP()
        Dim proj As Project
        Dim doc As Document
        Dim name As String

        doc = DTE.ActiveDocument
        name = doc.Name

        If name.EndsWith(".h") Then
            name = name.Replace(".h", ".cpp")
        ElseIf name.EndsWith(".cpp") Then
            name = name.Replace(".cpp", ".h")
        End If

        For Each proj In DTE.Solution.Projects
            If WalkProjectItemsAndOpen(proj.ProjectItems, name) Then
                Exit Sub
            End If
        Next

        Beep()

    End Sub

End Module

History

  • 20th September, 2002 - Updated Pierre Arnaud's solution to stop an exception being thrown in certain circumstances
  • 2nd June, 2008 - Fixed a typo in WalkProjectItemsAndOpen

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Authors

Pavel Sokolov
Web Developer
Russian Federation Russian Federation
C++ programmer.

Pierre Arnaud
Web Developer
Switzerland Switzerland

Pierre Arnaud got a Ph.D. in computer science at the Swiss Federal Institute of Technology; he currently works both as an independent contractor on hardware and software projects at OPaC bright ideas and as a senior software designer at EPSITEC.


Pierre was a key contributor to the Smaky computer, a real time, multitasking system based on the Motorola 680x0 processor family.


Now, Pierre works on his spare time for the Creative Docs .NET project: it is a vector based drawing and page layout software based on .NET and AGG.


You may also be interested in...

Pro

Comments and Discussions

 
AnswerBuilt-In Feature in VS2012 Pin
Darren Hickling1-Aug-13 7:04
memberDarren Hickling1-Aug-13 7:04 
QuestionTry this Pin
Dave Kerr4-Feb-12 0:05
mvpDave Kerr4-Feb-12 0:05 
GeneralVisual Studio plugin that does this Pin
eggplantriot8-Apr-10 21:01
membereggplantriot8-Apr-10 21:01 
GeneralRe: Visual Studio plugin that does this Pin
Howard Robinson15-Sep-10 5:58
memberHoward Robinson15-Sep-10 5:58 
Generaltypo Pin
kamnas2-Jun-08 2:09
memberkamnas2-Jun-08 2:09 
AnswerVisual Studio 2005 Header Switch Macro [modified] Pin
Snakefoot21-Jun-06 4:21
memberSnakefoot21-Jun-06 4:21 
Adjusted the macro so it can be used for Visual Studio 2005

New Improved Search order:
1. Look in open documents (Inspired by Switch between Header and CPP file)
2. Look in the same directory as the opponent file
3. Look through all projects in the entire solution using DTE.Solution.FindProjectItem (Inspired by robertwrose.com)
4. Look through all include paths in the attached projects (Inspired by BorisJ's Blog)

The search of include paths, requires that one adds a reference to Microsoft.VisualStudio.VCProjectEngine

To install the macro do the following:

1. Start Visual Studio 2005
2. In the menu select Tools -> Macros -> Macro Explorer.
3. In the Macro Explorer right-click "MyMacros" and choose "New Module..."
4. Create a new Module with the name "Opac"
5. In the Macro Explorer double-click the newly created module "Opac".
6. In the Macro IDE overwrite the contents with the big chunk of code below
7. In the Macro IDE Project Explorer right-click References and choose Add Reference... to add:
Microsoft.VisualStudio.VCProjectEngine
To assign a keyboard shortcut-key to the macro do the following:
1. Start Visual Studio 2005
2. In the menu select Tools -> Customize
3. Press the "Keyboard..." button
4. In the "Search Commands Containing" search for the name "Opac".
5. Change focus to "Press Shortcut keys" and assign a shortcut like CTRL+F6 (Or whatever)
6. Press "Assign" and THEN "Ok".

Enjoy

-Snakefoot

Option Strict Off
Option Explicit Off

Imports EnvDTE
Imports System.Diagnostics
' add reference to Microsoft.VisualStudio.VCProjectEngine
Imports Microsoft.VisualStudio.VCProjectEngine


Public Module Opac

    Function OpenLocalFile(ByVal sFile As String) As Boolean
        If My.Computer.FileSystem.FileExists(sFile) Then
            On Error Resume Next
            DTE.ItemOperations.OpenFile(sFile, Constants.vsViewKindCode)
            OpenLocalFile = (Err.Number = 0)
            Err.Clear()
            On Error GoTo 0
        Else
            OpenLocalFile = False
        End If
    End Function

    Function FilePath(ByVal file)
        'DESCRIPTION: Returns file path (without the trailing backslash "\").
        Dim iPos, iBS, strPath

        strPath = file
        iBS = Nothing
        Do While True
            iPos = InStr(1, file, "\", 1)
            If iPos = 0 Or iPos = Nothing Then
                Exit Do
            Else
                file = Right(file, Len(file) - iPos)
                iBS = iPos
            End If
        Loop

        If iBS = Nothing Then
            FilePath = ""
        Else
            FilePath = Left(strPath, Len(strPath) - Len(file) - 1)
        End If
    End Function


    Sub Swap_H_CPP()
        Dim name As String

        If ReferenceEquals(DTE.ActiveDocument, Nothing) Then
            DTE.StatusBar.Text = "Error no active document"
            Exit Sub
        End If

        If DTE.ActiveDocument.Language <> EnvDTE.Constants.dsCPP Then
            DTE.StatusBar.Text = "Error not a C++ document"
            Exit Sub
        End If

        name = DTE.ActiveDocument.Name.ToLower

        ' Try to switch from '.h' to '.cpp' then vice versa
        If name.EndsWith(".h") Then
            name = name.Replace(".h", ".cpp")
        ElseIf name.EndsWith(".hpp") Then
            name = name.Replace(".hpp", ".cpp")
        ElseIf name.EndsWith(".cpp") Then
            name = name.Replace(".cpp", ".h")
        ElseIf name.EndsWith(".c") Then
            name = name.Replace(".c", ".h")
        Else
            DTE.StatusBar.Text = "Error " + name + " has an unknown file-extension"
            Exit Sub
        End If

        DTE.StatusBar.Text = "Searching for " + name + " ..."

        ' Search open documents
        Dim iDoc As Integer
        For iDoc = 1 To DTE.Documents.Count
            If DTE.Documents.Item(iDoc).Name.ToLower = name Then
                OpenLocalFile(DTE.Documents.Item(iDoc).FullName)
                DTE.StatusBar.Text = "Ready"
                Exit Sub
            End If
        Next iDoc

        ' Search current directory
        If OpenLocalFile(DTE.ActiveDocument.Path & name) Then
            DTE.StatusBar.Text = "Ready"
            Exit Sub
        End If

        ' Attempt to find document in solution
        Dim item As EnvDTE.ProjectItem
        item = DTE.Solution.FindProjectItem(name)
        If Not ReferenceEquals(item, Nothing) Then
            If OpenLocalFile(item.FileNames(0)) Then
                DTE.StatusBar.Text = "Ready"
                Exit Sub
            End If
        End If

        ' Attempt to find document in include paths (Requires Microsoft.VisualStudio.VCProjectEngine reference)
        For Each proj As Project In DTE.Solution.Projects
            Dim vcProj As VCProject = proj.Object
            If Not ReferenceEquals(vcProj, Nothing) Then
                Dim configs As IVCCollection = vcProj.Configurations
                Dim index As Integer
                For index = 1 To configs.Count
                    Dim cfg As VCConfiguration = configs.Item(index)
                    Dim tools As IVCCollection = cfg.Tools
                    Dim compilerTool As VCCLCompilerTool = tools.Item("VCCLCompilerTool")

                    Dim path As String
                    For Each path In compilerTool.FullIncludePath.Split(";")
                        ' if relative path then adjust filepath accordingly
                        If InStr(path, "..") <> 0 Then
                            sFilePath = FilePath(proj.FullName)
                            Do While InStr(path, "..") <> 0
                                sFilePath = Left(sFilePath, InStrRev(sFilePath, "\") - 1)
                                path = Right(path, Len(path) - InStr(path, "..") - 1)
                            Loop
                            path = sFilePath + path
                        End If

                        If OpenLocalFile(path + "\" + name) Then
                            DTE.StatusBar.Text = "Ready"
                            Exit Sub
                        End If
                    Next
                Next
            End If
        Next

        DTE.StatusBar.Text = "Error File " + name + " could not be found in solution"
        Beep()

    End Sub

End Module


-- modified at 5:45 Thursday 30th November, 2006 (Now using DTE.Solution.FindProjectItem)
GeneralRe: Visual Studio 2005 Header Switch Macro Pin
jcem24-Feb-07 5:24
memberjcem24-Feb-07 5:24 
GeneralYet another adaptation... Pin
antoinecloutier27-Apr-06 15:39
memberantoinecloutier27-Apr-06 15:39 
GeneralCumulative VC++ 2003 (ver 7.1.3088) CPP-H-Swapper Pin
TedimDim1-Apr-06 2:50
memberTedimDim1-Apr-06 2:50 
GeneralRe: Cumulative VC++ 2003 (ver 7.1.3088) CPP-H-Swapper Pin
Pierre Arnaud1-Apr-06 20:52
memberPierre Arnaud1-Apr-06 20:52 
GeneralHOW Pin
alan937-Apr-05 6:12
memberalan937-Apr-05 6:12 
GeneralFolder problem Pin
Mr Scotty5-Jan-05 5:17
memberMr Scotty5-Jan-05 5:17 
GeneralExcellent Pin
Anonymous28-Nov-03 0:38
sussAnonymous28-Nov-03 0:38 
QuestionHow to install? Pin
Anonymous7-Nov-03 2:18
sussAnonymous7-Nov-03 2:18 
QuestionHow to install? Pin
Anonymous7-Nov-03 2:18
sussAnonymous7-Nov-03 2:18 
AnswerI have the same problem in VS .NET 2003 Pin
Skyhawk13-Jan-04 13:13
memberSkyhawk13-Jan-04 13:13 
GeneralRe: I have the same problem in VS .NET 2003 Pin
Pavel Sokolov22-Jan-04 22:28
memberPavel Sokolov22-Jan-04 22:28 
GeneralRe: I have the same problem in VS .NET 2003 Pin
Shroombaker19-Apr-04 13:11
memberShroombaker19-Apr-04 13:11 
GeneralRe: I have the same problem in VS .NET 2003 Pin
Rehan A30-Apr-04 8:36
sussRehan A30-Apr-04 8:36 
AnswerRe: How to install? Pin
Alan Balkany17-Mar-10 8:22
memberAlan Balkany17-Mar-10 8:22 
GeneralFix for filename case sensitivity Pin
hgohel21-Sep-03 7:38
memberhgohel21-Sep-03 7:38 
GeneralFix for VS .NET 2003 Pin
dr00g8-May-03 0:43
memberdr00g8-May-03 0:43 
GeneralRe: Fix for VS .NET 2003 Pin
Todd C. Gleason28-Aug-03 8:00
memberTodd C. Gleason28-Aug-03 8:00 
GeneralThis doesn't work in Final Beta 2003 Pin
Nevering22-Mar-03 13:58
memberNevering22-Mar-03 13:58 
GeneralRe: This doesn't work in Final Beta 2003 Pin
Nevering22-Mar-03 14:11
memberNevering22-Mar-03 14:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.180111.1 | Last Updated 3 Jun 2008
Article Copyright 2002 by Pavel Sokolov, Pierre Arnaud
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid