英文:
Visual Studio IDE - How to Use Visual Studio Commands in Custom Extensions?
问题
我是新手开发 Visual Studio 扩展,我尝试创建一个扩展,可以运行 Visual Studio 的 "Replace in Files"(编辑.ReplaceinFiles)命令,然后自动运行 "Navigate Backwards"(查看.NavigateBackward)命令,以确保在替换代码行后视图不会跳到下一个匹配结果。
在测试正则表达式(regex)时,防止视图在我决定之前移动将非常有帮助,因为这可以让我验证文本是否被正确替换,然后再移动到下一个文件或同一文档中的下一个匹配代码行。
我按照这个教程创建了一个基本扩展:链接,使用了 Extensibility Essentials 2022 命令模板。但在尝试使用 DTE 代码运行 Visual Studio 命令时,我遇到了以下错误:
CSOI 03: The name 'GetService' does not exist in the current context
以下是我正在使用的 "MyCommand.cs" VSIX 项目文件中的代码。请问我需要做什么来使 DTE 代码工作,或者是否有更好的方法来运行扩展中的 Visual Studio 命令?
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'm new to developing Visual Studio Extensions and I'm trying to make my 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");
}
}
}
答案1
得分: 1
以下是翻译好的部分:
我正在遵循这份官方文档,最终我能够在我的自定义扩展中使用 Visual Studio 命令:
Tutorial - 创建您的第一个扩展:Hello World
这是我这边的关键文件:
Command1.cs:
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using System;
using System.ComponentModel.Design;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Task = System.Threading.Tasks.Task;
using EnvDTE;
using EnvDTE80;
namespace HelloWorld
{
/// <summary>
/// 命令处理程序
/// </summary>
internal sealed class Command1
{
// ...
}
}
HelloWorldPackage.vsct
<?xml version="1.0" encoding="utf-8"?>
<CommandTable xmlns="http://schemas.microsoft.com/VisualStudio/2005-10-18/CommandTable" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<!-- 这是定义命令的实际布局和类型的文件。它分为不同的部分(例如命令定义、命令放置等),每个部分定义了一组特定的属性。请参见每个部分前面的注释,了解如何使用它。 -->
<!-- ...
-->
</CommandTable>
关键代码是:
using EnvDTE;
using EnvDTE80;
还有在 Execute
方法中的关键代码:
// 获取 DTE 对象
DTE dte = Package.GetGlobalService(typeof(DTE)) as DTE;
// 执行 Edit.LineEnd 命令
dte.ExecuteCommand("Edit.LineEnd");
经过以下更改后,当我启动一个实例进行测试时,我将看到鼠标光标能够在单击我的自定义扩展的命令后移动到行的末尾。
英文:
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:
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using System;
using System.ComponentModel.Design;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Task = System.Threading.Tasks.Task;
using EnvDTE;
using EnvDTE80;
namespace HelloWorld
{
/// <summary>
/// Command handler
/// </summary>
internal sealed class Command1
{
/// <summary>
/// Command ID.
/// </summary>
public const int CommandId = 0x0100;
/// <summary>
/// Command menu group (command set GUID).
/// </summary>
public static readonly Guid CommandSet = new Guid("0bc830f1-cce9-474a-8e2c-0bd277de045c");
/// <summary>
/// VS Package that provides this command, not null.
/// </summary>
private readonly AsyncPackage package;
/// <summary>
/// Initializes a new instance of the <see cref="Command1"/> class.
/// Adds our command handlers for menu (commands must exist in the command table file)
/// </summary>
/// <param name="package">Owner package, not null.</param>
/// <param name="commandService">Command service to add command to, not null.</param>
private Command1(AsyncPackage package, OleMenuCommandService commandService)
{
this.package = package ?? throw new ArgumentNullException(nameof(package));
commandService = commandService ?? throw new ArgumentNullException(nameof(commandService));
var menuCommandID = new CommandID(CommandSet, CommandId);
var menuItem = new MenuCommand(this.Execute, menuCommandID);
commandService.AddCommand(menuItem);
}
/// <summary>
/// Gets the instance of the command.
/// </summary>
public static Command1 Instance
{
get;
private set;
}
/// <summary>
/// Gets the service provider from the owner package.
/// </summary>
private Microsoft.VisualStudio.Shell.IAsyncServiceProvider ServiceProvider
{
get
{
return this.package;
}
}
/// <summary>
/// Initializes the singleton instance of the command.
/// </summary>
/// <param name="package">Owner package, not null.</param>
public static async Task InitializeAsync(AsyncPackage package)
{
// Switch to the main thread - the call to AddCommand in Command1's constructor requires
// the UI thread.
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(package.DisposalToken);
OleMenuCommandService commandService = await package.GetServiceAsync(typeof(IMenuCommandService)) as OleMenuCommandService;
Instance = new Command1(package, commandService);
}
/// <summary>
/// This function is the callback used to execute the command when the menu item is clicked.
/// See the constructor to see how the menu item is associated with this function using
/// OleMenuCommandService service and MenuCommand class.
/// </summary>
/// <param name="sender">Event sender.</param>
/// <param name="e">Event args.</param>
private void Execute(object sender, EventArgs e)
{
// Get DTE Object
DTE dte = Package.GetGlobalService(typeof(DTE)) as DTE;
// Execute Edit.LineEnd command
dte.ExecuteCommand("Edit.LineEnd");
ThreadHelper.ThrowIfNotOnUIThread();
string message = "Hello World!";
string title = "Command1";
// Show a message box to prove we were here
VsShellUtilities.ShowMessageBox(
this.package,
message,
title,
OLEMSGICON.OLEMSGICON_INFO,
OLEMSGBUTTON.OLEMSGBUTTON_OK,
OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
}
}
}
HelloWorldPackage.vsct
<?xml version="1.0" encoding="utf-8"?>
<CommandTable xmlns="http://schemas.microsoft.com/VisualStudio/2005-10-18/CommandTable" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<!-- This is the file that defines the actual layout and type of the commands.
It is divided in different sections (e.g. command definition, command
placement, ...), with each defining a specific set of properties.
See the comment before each section for more details about how to
use it. -->
<!-- The VSCT compiler (the tool that translates this file into the binary
format that VisualStudio will consume) has the ability to run a preprocessor
on the vsct file; this preprocessor is (usually) the C++ preprocessor, so
it is possible to define includes and macros with the same syntax used
in C++ files. Using this ability of the compiler here, we include some files
defining some of the constants that we will use inside the file. -->
<!--This is the file that defines the IDs for all the commands exposed by VisualStudio. -->
<Extern href="stdidcmd.h"/>
<!--This header contains the command ids for the menus provided by the shell. -->
<Extern href="vsshlids.h"/>
<!--The Commands section is where commands, menus, and menu groups are defined.
This section uses a Guid to identify the package that provides the command defined inside it. -->
<Commands package="guidHelloWorldPackage">
<!-- Inside this section we have different sub-sections: one for the menus, another
for the menu groups, one for the buttons (the actual commands), one for the combos
and the last one for the bitmaps used. Each element is identified by a command id that
is a unique pair of guid and numeric identifier; the guid part of the identifier is usually
called "command set" and is used to group different command inside a logically related
group; your package should define its own command set in order to avoid collisions
with command ids defined by other packages. -->
<!-- In this section you can define new menu groups. A menu group is a container for
other menus or buttons (commands); from a visual point of view you can see the
group as the part of a menu contained between two lines. The parent of a group
must be a menu. -->
<Groups>
<Group guid="guidHelloWorldPackageCmdSet" id="MyMenuGroup" priority="0x0600">
<Parent guid="guidSHLMainMenu" id="IDM_VS_MENU_TOOLS"/>
</Group>
</Groups>
<!--Buttons section. -->
<!--This section defines the elements the user can interact with, like a menu command or a button
or combo box in a toolbar. -->
<Buttons>
<!--To define a menu group you have to specify its ID, the parent menu and its display priority.
The command is visible and enabled by default. If you need to change the visibility, status, etc, you can use
the CommandFlag node.
You can add more than one CommandFlag node e.g.:
<CommandFlag>DefaultInvisible</CommandFlag>
<CommandFlag>DynamicVisibility</CommandFlag>
If you do not want an image next to your command, remove the Icon node /> -->
<Button guid="guidHelloWorldPackageCmdSet" id="Command1Id" priority="0x0100" type="Button">
<Parent guid="guidHelloWorldPackageCmdSet" id="MyMenuGroup" />
<Icon guid="guidImages" id="bmpPic1" />
<Strings>
<ButtonText>Say Hello World!</ButtonText>
</Strings>
</Button>
</Buttons>
<!--The bitmaps section is used to define the bitmaps that are used for the commands.-->
<Bitmaps>
<!-- The bitmap id is defined in a way that is a little bit different from the others:
the declaration starts with a guid for the bitmap strip, then there is the resource id of the
bitmap strip containing the bitmaps and then there are the numeric ids of the elements used
inside a button definition. An important aspect of this declaration is that the element id
must be the actual index (1-based) of the bitmap inside the bitmap strip. -->
<Bitmap guid="guidImages" href="Resources\Command1.png" usedList="bmpPic1, bmpPic2, bmpPicSearch, bmpPicX, bmpPicArrows, bmpPicStrikethrough"/>
</Bitmaps>
</Commands>
<Symbols>
<!-- This is the package guid. -->
<GuidSymbol name="guidHelloWorldPackage" value="{e89d0a06-f62a-4e56-9a23-e9facaf8fa6b}" />
<!-- This is the guid used to group the menu commands together -->
<GuidSymbol name="guidHelloWorldPackageCmdSet" value="{0bc830f1-cce9-474a-8e2c-0bd277de045c}">
<IDSymbol name="MyMenuGroup" value="0x1020" />
<IDSymbol name="Command1Id" value="0x0100" />
</GuidSymbol>
<GuidSymbol name="guidImages" value="{88790f66-51b1-469c-8a26-7fac8e19701b}" >
<IDSymbol name="bmpPic1" value="1" />
<IDSymbol name="bmpPic2" value="2" />
<IDSymbol name="bmpPicSearch" value="3" />
<IDSymbol name="bmpPicX" value="4" />
<IDSymbol name="bmpPicArrows" value="5" />
<IDSymbol name="bmpPicStrikethrough" value="6" />
</GuidSymbol>
</Symbols>
</CommandTable>
The key code is:
using EnvDTE;
using EnvDTE80;
And this the key code in the Execute method:
// Get DTE Object
DTE dte = Package.GetGlobalService(typeof(DTE)) as DTE;
// Execute Edit.LineEnd command
dte.ExecuteCommand("Edit.LineEnd");
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论