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

huangapple go评论73阅读模式
英文:

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
{
    /// &lt;summary&gt;
    /// Command handler
    /// &lt;/summary&gt;
    internal sealed class Command1
    {
        /// &lt;summary&gt;
        /// Command ID.
        /// &lt;/summary&gt;
        public const int CommandId = 0x0100;

        /// &lt;summary&gt;
        /// Command menu group (command set GUID).
        /// &lt;/summary&gt;
        public static readonly Guid CommandSet = new Guid(&quot;0bc830f1-cce9-474a-8e2c-0bd277de045c&quot;);

        /// &lt;summary&gt;
        /// VS Package that provides this command, not null.
        /// &lt;/summary&gt;
        private readonly AsyncPackage package;

        /// &lt;summary&gt;
        /// Initializes a new instance of the &lt;see cref=&quot;Command1&quot;/&gt; class.
        /// Adds our command handlers for menu (commands must exist in the command table file)
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;package&quot;&gt;Owner package, not null.&lt;/param&gt;
        /// &lt;param name=&quot;commandService&quot;&gt;Command service to add command to, not null.&lt;/param&gt;
        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);
        }

        /// &lt;summary&gt;
        /// Gets the instance of the command.
        /// &lt;/summary&gt;
        public static Command1 Instance
        {
            get;
            private set;
        }

        /// &lt;summary&gt;
        /// Gets the service provider from the owner package.
        /// &lt;/summary&gt;
        private Microsoft.VisualStudio.Shell.IAsyncServiceProvider ServiceProvider
        {
            get
            {
                return this.package;
            }
        }

        /// &lt;summary&gt;
        /// Initializes the singleton instance of the command.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;package&quot;&gt;Owner package, not null.&lt;/param&gt;
        public static async Task InitializeAsync(AsyncPackage package)
        {
            // Switch to the main thread - the call to AddCommand in Command1&#39;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);
        }

        /// &lt;summary&gt;
        /// 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.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;sender&quot;&gt;Event sender.&lt;/param&gt;
        /// &lt;param name=&quot;e&quot;&gt;Event args.&lt;/param&gt;
        private void Execute(object sender, EventArgs e)
        {

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

            // Execute Edit.LineEnd command
            dte.ExecuteCommand(&quot;Edit.LineEnd&quot;);

            ThreadHelper.ThrowIfNotOnUIThread();
            string message = &quot;Hello World!&quot;;
            string title = &quot;Command1&quot;;

            // 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

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;CommandTable xmlns=&quot;http://schemas.microsoft.com/VisualStudio/2005-10-18/CommandTable&quot; xmlns:xs=&quot;http://www.w3.org/2001/XMLSchema&quot;&gt;

  &lt;!--  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. --&gt;

  &lt;!--  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. --&gt;

  &lt;!--This is the file that defines the IDs for all the commands exposed by VisualStudio. --&gt;
  &lt;Extern href=&quot;stdidcmd.h&quot;/&gt;

  &lt;!--This header contains the command ids for the menus provided by the shell. --&gt;
  &lt;Extern href=&quot;vsshlids.h&quot;/&gt;

  &lt;!--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. --&gt;
  &lt;Commands package=&quot;guidHelloWorldPackage&quot;&gt;
    &lt;!-- 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 &quot;command set&quot; 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. --&gt;

    &lt;!-- 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. --&gt;
    &lt;Groups&gt;
      &lt;Group guid=&quot;guidHelloWorldPackageCmdSet&quot; id=&quot;MyMenuGroup&quot; priority=&quot;0x0600&quot;&gt;
        &lt;Parent guid=&quot;guidSHLMainMenu&quot; id=&quot;IDM_VS_MENU_TOOLS&quot;/&gt;
      &lt;/Group&gt;
    &lt;/Groups&gt;

    &lt;!--Buttons section. --&gt;
    &lt;!--This section defines the elements the user can interact with, like a menu command or a button
        or combo box in a toolbar. --&gt;
    &lt;Buttons&gt;
      &lt;!--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.:
              &lt;CommandFlag&gt;DefaultInvisible&lt;/CommandFlag&gt;
              &lt;CommandFlag&gt;DynamicVisibility&lt;/CommandFlag&gt;
          If you do not want an image next to your command, remove the Icon node /&gt; --&gt;
      &lt;Button guid=&quot;guidHelloWorldPackageCmdSet&quot; id=&quot;Command1Id&quot; priority=&quot;0x0100&quot; type=&quot;Button&quot;&gt;
        &lt;Parent guid=&quot;guidHelloWorldPackageCmdSet&quot; id=&quot;MyMenuGroup&quot; /&gt;
        &lt;Icon guid=&quot;guidImages&quot; id=&quot;bmpPic1&quot; /&gt;
        &lt;Strings&gt;
          &lt;ButtonText&gt;Say Hello World!&lt;/ButtonText&gt;
        &lt;/Strings&gt;
      &lt;/Button&gt;
    &lt;/Buttons&gt;

    &lt;!--The bitmaps section is used to define the bitmaps that are used for the commands.--&gt;
    &lt;Bitmaps&gt;
      &lt;!--  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. --&gt;
      &lt;Bitmap guid=&quot;guidImages&quot; href=&quot;Resources\Command1.png&quot; usedList=&quot;bmpPic1, bmpPic2, bmpPicSearch, bmpPicX, bmpPicArrows, bmpPicStrikethrough&quot;/&gt;
    &lt;/Bitmaps&gt;
  &lt;/Commands&gt;

  &lt;Symbols&gt;
    &lt;!-- This is the package guid. --&gt;
    &lt;GuidSymbol name=&quot;guidHelloWorldPackage&quot; value=&quot;{e89d0a06-f62a-4e56-9a23-e9facaf8fa6b}&quot; /&gt;

    &lt;!-- This is the guid used to group the menu commands together --&gt;
    &lt;GuidSymbol name=&quot;guidHelloWorldPackageCmdSet&quot; value=&quot;{0bc830f1-cce9-474a-8e2c-0bd277de045c}&quot;&gt;
      &lt;IDSymbol name=&quot;MyMenuGroup&quot; value=&quot;0x1020&quot; /&gt;
      &lt;IDSymbol name=&quot;Command1Id&quot; value=&quot;0x0100&quot; /&gt;
    &lt;/GuidSymbol&gt;

    &lt;GuidSymbol name=&quot;guidImages&quot; value=&quot;{88790f66-51b1-469c-8a26-7fac8e19701b}&quot; &gt;
      &lt;IDSymbol name=&quot;bmpPic1&quot; value=&quot;1&quot; /&gt;
      &lt;IDSymbol name=&quot;bmpPic2&quot; value=&quot;2&quot; /&gt;
      &lt;IDSymbol name=&quot;bmpPicSearch&quot; value=&quot;3&quot; /&gt;
      &lt;IDSymbol name=&quot;bmpPicX&quot; value=&quot;4&quot; /&gt;
      &lt;IDSymbol name=&quot;bmpPicArrows&quot; value=&quot;5&quot; /&gt;
      &lt;IDSymbol name=&quot;bmpPicStrikethrough&quot; value=&quot;6&quot; /&gt;
    &lt;/GuidSymbol&gt;
  &lt;/Symbols&gt;
&lt;/CommandTable&gt;

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(&quot;Edit.LineEnd&quot;);

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.

huangapple
  • 本文由 发表于 2023年7月17日 20:51:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76704656.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定