Visual Studio IDE - 如何在自定义扩展中使用 Visual Studio 命令?

问题描述 投票:0回答:1

我是开发 Visual Studio 扩展的新手,我正在尝试制作一个运行 Visual Studio 的“在文件中替换”(Edit.ReplaceinFiles) 命令,然后自动运行向后导航 (View.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");
        }
    }
}
visual-studio-2022 visual-studio-extensions vsix envdte vs-extensibility
1个回答
2
投票

我按照这个官方文档,终于可以在我的自定义扩展中使用 Visual Studio 命令了:

教程 - 创建您的第一个扩展: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>
    /// 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>

关键代码是:

using EnvDTE;
using EnvDTE80;

这是 Execute 方法中的关键代码:

    // Get DTE Object
    DTE dte = Package.GetGlobalService(typeof(DTE)) as DTE;

    // Execute Edit.LineEnd command
    dte.ExecuteCommand("Edit.LineEnd");

进行以下更改后,在我启动实例进行测试后,单击我的自定义扩展的命令后,我将看到鼠标光标能够移动到行尾。

© www.soinside.com 2019 - 2024. All rights reserved.