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



我想在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);
                }
            }          
        }
    }
}

相关内容

最新更新