How do I retrieve the selected code from a Code Window, or Text Document, modify it, and replace the selection in the window? This is one of the most elementary, but often used features required in an add-in. The code developed in this article will provide that functionality.
First, I will show the code for retrieving the selected block of code or text. The only requirement to use the following code is that oVS be set to the application object of the IDE. The function returns the selected block of code. The TextSelection object is a fundamental object for manipulating text in a code window. You can look up this object in MSDN to see its many methods and properties. I also deal extensively with the TextSelection and EditPoint objects in my book on Writing Add-ins for Visual Studio .NET, published by Apress. You can purchase it very reasonably at Amazon.Com.
| Public Function GetCodeFromWindow() As String Dim selCodeBlock As TextSelection Try selCodeBlock = CType(oVS.ActiveDocument.Selection(), _ EnvDTE.TextSelection) GetCodeFromWindow = selCodeBlock.Text Catch ex As System.Exception ' Provide your error handling code End Try End Function |
| Friend Sub PutCodeBack(ByVal s As String) Dim selCodeBlock As TextSelection Try selCodeBlock = CType(oVS.ActiveDocument.Selection(), _ EnvDTE.TextSelection) selCodeBlock.Delete() selCodeBlock.Insert(s, 1) ' This code will reindent the entire document ' after an insertion to ensure it is indented properly ' it will only work for VB, as the C# editor only has ' the ability to format a selection, and placing the ' code back in the window loses the selection Try oVS.ExecuteCommand("Edit.FormatDocument") Catch End Try Catch ex As System.Exception ' Provide your error handling code End Try End Sub |
| Public Function IsStringTerminatedByCRLF(ByVal s As String) _ As String ' Returns passed string with a crlf appended ' if the last char is not ' a cr,lf, or crlf, otherwise returns s. Dim sLC As String = s.Substring(s.Length - 1, 1) If sLC = vbCr Or sLC = vbLf Then Return s Else Return s & vbCrLf End If End Function |