【问题标题】:How to access current code editor from tool window?如何从工具窗口访问当前代码编辑器?
【发布时间】:2019-09-04 07:53:55
【问题描述】:

我目前正在尝试使用“Visual Studio 2015”为此创建扩展。 我想创建一个函数,当单击 ToolWindow 的按钮时,该函数将适合当前代码编辑器光标部分的源代码插入。 SDK 模板中有一个 ToolWindow 示例。 但是,是在ToolWindow中完成的,没有编写进入代码编辑器的方法。 如何从 ToolWindow 获取/设置当前代码编辑器源代码?

【问题讨论】:

标签: c# visual-studio-2015 visual-studio-extensions


【解决方案1】:

正如 Sergey 建议的那样,我们可以使用 TextSelection.Text 属性。

但不知何故,我未能以这种方式获得 VS2015 的选择:DTE.ActiveDocument.Selection。

对我来说,在VS2015中我新建了一个custom Tool Window项,在ToolWindow中添加了一个简单的TextBox控件,然后双击默认的Click me!按钮导航到ToolWindow1Control.xaml.cs中的button-Click方法文件,然后我添加如下代码以从文本框中获取文本并将其插入编辑器:

        [SuppressMessage("Microsoft.Globalization", "CA1300:SpecifyMessageBoxOptions", Justification = "Sample code")]
        [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1300:ElementMustBeginWithUpperCaseLetter", Justification = "Default event handler naming pattern")]
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            string text = textBox.Text;
            DTE dte = Package.GetGlobalService(typeof(DTE)) as DTE;
            (dte.ActiveDocument.Selection as EnvDTE.TextSelection).Text = text;
        }

所以对我来说,我实际上是使用下面的代码来插入文本:

        DTE dte = Package.GetGlobalService(typeof(DTE)) as DTE;
        (dte.ActiveDocument.Selection as EnvDTE.TextSelection).Text = "Add your text here."; 

另外:

要使用上面的代码,你需要在ToolWindow1Control.xaml.cs文件中添加定义:

        using Microsoft.VisualStudio.Shell;
        using EnvDTE;

希望对你有所帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-06
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-11
    相关资源
    最近更新 更多