Visual Studio 2008 のアドインを作成する。指定したファイルの指定した行番号にジャンプする。
Visual Studio 2008 のアドインからIDEを操作する場合は、EnvDTE80.DTE2オブジェクトを使います。EnvDTE80.DTE2は、IDEのオブジェクトモデルそのもので基本的な操作が一通りできるようになっています。
今回は、指定したファイルを開いて、指定した行番号にカーソルを合わせるという操作を行います。
- 現在開いているウインドウの中に、指定したファイルが存在するか確認する。
- 存在しない場合はファイルを開く。
- 対象ファイルのウインドウに対して、TextSelectionオブジェクトを使用して指定した行番号にカーソルを合わせる。
という手順で行います。
現在開いているウインドウの中に、指定したファイルが存在するか確認する。
Dim targetWindow As EnvDTE.Window = NothingFor Each win As EnvDTE.Window In application.Windows
If win.Document Is Nothing Then
Continue For
End IfIf String.Compare(targetFile, win.Document.FullName, True) = 0 Then
targetWindow = win
Exit For
End IfNext
存在しない場合はファイルを開く。
If targetWindow Is Nothing Then
targetWindow = application.ItemOperations.OpenFile(targetFile, EnvDTE.Constants.vsViewKindPrimary)
End If
対象ファイルのウインドウに対して、TextSelectionオブジェクトを使用して指定した行番号にカーソルを合わせる。
Dim ts As TextSelection = CType(targetWindow.Selection, TextSelection)ts.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, False)
ts.EndOfLine(False)
ts.GotoLine(targetLineNo, True)targetWindow.Activate()
以下、全コードとなります。
Imports System
Imports Microsoft.VisualStudio.CommandBars
Imports Extensibility
Imports EnvDTE
Imports EnvDTE80Public Class DTE2Utils
Public Shared Sub OpenFileAndJumpLineNo(ByVal application As DTE2, _
ByVal targetFile As String, _
ByVal targetLineNo As Integer)Try
Dim targetWindow As EnvDTE.Window = Nothing
For Each win As EnvDTE.Window In application.Windows
If win.Document Is Nothing Then
Continue For
End IfIf String.Compare(targetFile, win.Document.FullName, True) = 0 Then
targetWindow = win
Exit For
End IfNext
If targetWindow Is Nothing Then
targetWindow = application.ItemOperations.OpenFile(targetFile, EnvDTE.Constants.vsViewKindPrimary)
End IfDim ts As TextSelection = CType(targetWindow.Selection, TextSelection)
ts.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText, False)
ts.EndOfLine(False)
ts.GotoLine(targetLineNo, True)targetWindow.Activate()
Catch ex As Exception
Debug.Print(ex.Message)
End Try
End Sub
End Class