【问题标题】:How can I run custom tool or save a file programmatically using EnvDTE?如何使用 EnvDTE 以编程方式运行自定义工具或保存文件?
【发布时间】:2023-04-01 19:05:01
【问题描述】:

我想在我的扩展程序中的几个 .tt 文件上保存/运行自定义工具。我不想遍历解决方案/项目中的所有文件,而是希望能够使用文件的相对(或完整)路径来执行保存/运行自定义工具。

有没有办法在给定文件路径 ($(SolutionDir)/MyProject/MyFile.tt) 的情况下获取 ProjectItem 对象,以便我可以对其执行方法?

【问题讨论】:

    标签: visual-studio-extensions envdte


    【解决方案1】:

    您可以使用EnvDTE.Solution 类型的FindProjectItem 方法在当前解决方案中按文件名查找文件。 ExecuteCommand 方法依赖于当前的 UI 上下文;所以必须选中该项,否则调用失败。

    private bool TryExecuteTextTemplate(string filename)
    {
        var dte = (DTE2)this.GetService(typeof(SDTE));
        Solution solution = dte.Solution;
        if ((solution != null) && solution.IsOpen)
        {
            VSProjectItem projectItem;
            ProjectItem item = solution.FindProjectItem(filename);
            if (item != null && ((projectItem = item.Object as VSProjectItem) != null))
            {
                // TODO: track the item in the Solution Explorer
    
                try
                {
                    projectItem.RunCustomTool();
                    return true;
                }
                catch (COMException) 
                { 
                }
            }
        }
    
        return false;
    }
    

    【讨论】:

    • 我必须使用(item.Object as VSProjectItem).RunCustomTool();而不是item.DTE.ExecuteCommand("Project.RunCustomTool");
    • 正如 Omar 所说(dte.Solution.FindProjectItem(path).Object as VSProjectItem).RunCustomTool() 也为我工作。还需要引用 VSLangProj.dll。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-23
    • 1970-01-01
    • 1970-01-01
    • 2018-02-28
    • 1970-01-01
    相关资源
    最近更新 更多