[英]Get the reference of the DTE object in Visual C# 2015
我想在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);
}
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.