I'm new to developing Visual Studio Extensions and I'm trying to make one that runs Visual Studio's "Replace in Files" (Edit.ReplaceinFiles) command and then automatically runs the Navigate Backwards (View.NavigateBackward) command so that the view doesn't move to the next matching result after replacing a line of code.
Preventing the view from moving until I decide so would be very helpful when testing REGEX (regular expressions) in the find-and-replace command as it would allow me to verify that text was replaced properly before moving to the next file or next matching code line in the same document.
I followed this tutorial for creating a basic extension using a Extensibility Essentials 2022 Command template and upon trying to use DTE code to run a visual studio command I get the following error:
CSOI 03: The name 'GetService' does not exist in the current context
Below is the code from my "MyCommand.cs" VSIX project file that I'm working from. What exactly do I have to do to make the DTE code work or is there a better way of trying to run Visual Studio Commands from an extension?
using System.ComponentModel.Composition;
using System.Linq;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Tassk = System.Threading.Tasks.Task;
namespace ReplaceNoScroll
{
[Command(PackageIds.MyCommand)]
internal sealed class MyCommand : BaseCommand<MyCommand>
{
protected override async Task ExecuteAsync(OleMenuCmdEventArgs e)
{
//Get reference to the current active document
var docView = await VS.Documents.GetActiveDocumentViewAsync();
// Get the DTE object
var dte = (EnvDTE80.DTE2)GetService(typeof(EnvDTE.DTE));
// Execute the "Navigate Backwards" command
dte.ExecuteCommand("View.NavigateBackward");
}
}
}
I am following this official document, and finally I am able to use Visual Studio Commands in my custom extension:
Tutorial - Create your first extension: Hello World
Here are the key files on my side:
Command1.cs:
HelloWorldPackage.vsct
The key code is:
And this the key code in the Execute method:
After the below changes, after I start a instance to test, I will see the mouse cursor be able to move to the end of the line after click the command of my custom extension.