c# - 在 Visual C# 2015 中获取 DTE 对象的引用

标签 c#

我想获取当前解决方案的引用,在 Visual Studio 2015 中使用 C# 的 DTE 对象。

using System;
using EnvDTE;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;

namespace TemplatesExample
{
    class Program
    {
        static void Main(string[] args)
        {
            IVsSolution solution = Package.GetGlobalService(typeof(DTE)) as IVsSolution;

            Console.WriteLine(solution.ToString());

            Console.ReadKey();

        }

    }
}

但是当我使用它时,我的解决方案对象始终为 NULL。

那么如何在 .net Framework 4.6 上使用 C# 获取 VS2015 中当前的解决方案对象?

最佳答案

尝试这个示例。在 VS2015 上启动并运行。 (此方法仅对同一解有效)。

using EnvDTE;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace Test
{
    public partial class Form1 : Form
    {
        public class DTEHandle
        {
            //EnvDTE.Project proj;
            //EnvDTE.Configuration config;
            //EnvDTE.Properties configProps;
            //EnvDTE.Property prop;
            EnvDTE.DTE DTE = Marshal.GetActiveObject("VisualStudio.DTE.14.0") as EnvDTE.DTE;
            public EnvDTE.Project GetProject(String Name)
            {
                foreach (EnvDTE.Project item in DTE.Solution.Projects)
                {
                    if (item.Name == Name)
                    {
                        return item;
                    }
                }
                return null;
            }
        }

        public Form1()
        {
            InitializeComponent();
            EnvDTE.DTE DTE = Marshal.GetActiveObject("VisualStudio.DTE.14.0") as EnvDTE.DTE;

            DTEHandle h = new DTEHandle();
            EnvDTE.Project proj = h.GetProject("Test");

            foreach (EnvDTE.ProjectItem item in proj.ProjectItems)
            {
                if (item.Name == "Program.cs")
                {
                    TextSelection s = item.Document.Selection as TextSelection;
                    s.SelectAll();
                    MessageBox.Show(s.Text);
                }
            }          
        }
    }
}

关于c# - 在 Visual C# 2015 中获取 DTE 对象的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35986852/

相关文章:

c# - 验证字符串是否存在于列表中

c# - 突出显示标签 Windows 窗体

C# MVC 应用程序 - 在不丢失 session 数据的情况下更改 session ID

c# - 将 ObservableCollection 复制到另一个 ObservableCollection

c# - 如何在 LinQ 中合并多个集合

c# - 在 IE9 模式下 WebBrowser 控件中不需要的滚动条

c# - Unity 3d - 标签或重载函数?

c# - 无法从传输连接读取数据 : An established connection was aborted by the software in your host machine in C# .Net

c# - 使用 PKCE 登录 Discord OAuth 的过程

c# - 将值从 Object[,] 数组复制到 Object[][] 数组