【问题标题】:Get the reference of the DTE object in Visual C# 2015在 Visual C# 2015 中获取 DTE 对象的引用
【发布时间】:2016-03-14 11:53:52
【问题描述】:

我想在 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 中获取我当前的解决方案对象?

【问题讨论】:

标签: c#


【解决方案1】:

试试这个示例。在 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);
                }
            }          
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-25
    • 2010-12-13
    • 1970-01-01
    相关资源
    最近更新 更多