2016-03-14 31 views
2

我想以當前解決方案的參考的參考,使用與C#DTE對象在Visual Studio 2015年獲取在Visual C#DTE對象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(); 

     } 

    } 
} 

但是,當我用這個,我解決方案對象始終爲NULL。

那麼,如何使用.NET Framework 4.6中的C#在VS2015中獲得當前的解決方案對象?

+0

我跟了解決方案http://stackoverflow.com/questions/4724381/get-the-reference-of-the-dte2-object-in-visual-c-sharp-2010,但仍然問題沒有解決。 – user2790976

回答

2

試試這個例子。在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); 
       } 
      }   
     } 
    } 
}