简体   繁体   中英

Get the reference of the DTE object in Visual C# 2015

I want to get a reference to the current solution, using the DTE object with C# in Visual Studio 2015.

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();

        }

    }
}

But when I use this, my solution object is always NULL.

So how do I get to my current solution object in VS2015 using C# on .net framework 4.6?

Try this sample. Up and running on VS2015. ( This method is valid only for the same solution ).

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);
                }
            }          
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM