代码之家  ›  专栏  ›  技术社区  ›  Sarah Vessels

environmentevent宏未完成

  •  1
  • Sarah Vessels  · 技术社区  · 15 年前

    我在Visual Studio 2008中工作,我希望编辑>大纲显示>折叠到定义,以便在打开文件时运行。如果在那之后,所有地区都扩大了,那就更好了。我尝试了Kyralessa在评论中提供的代码 The Problem with Code Folding 作为一个必须手动运行的宏,它工作得非常好。我试图通过在宏IDE的environmentevents模块中放置以下代码来扩展此宏以充当事件:

    Public Sub documentEvents_DocumentOpened(ByVal Document As EnvDTE.Document) Handles DocumentEvents.DocumentOpened
        Document.DTE.ExecuteCommand("Edit.CollapsetoDefinitions")
        DTE.SuppressUI = True
        Dim objSelection As TextSelection = DTE.ActiveDocument.Selection
        objSelection.StartOfDocument()
        Do While objSelection.FindText("#region", vsFindOptions.vsFindOptionsMatchInHiddenText)
        Loop
        objSelection.StartOfDocument()
        DTE.SuppressUI = False
    End Sub
    

    但是,当我在中打开解决方案中的文件时,这似乎没有任何作用。为了测试宏是否正在运行,我将 MsgBox() 在该子例程中的语句并注意到 Document.DTE.ExecuteCommand("Edit.CollapsetoDefinitions") 跑得很好,但在那条线之后似乎什么都没有被击中。当我调试并在子例程中设置断点时,我将按F10继续到下一行,控件将尽快离开子例程。 ExecuteCommand 线路运行。尽管如此,这条线似乎什么都不做,即它不会折叠大纲。

    我也尝试使用 DTE.ExecuteCommand("Edit.CollapsetoDefinitions") 在子程序中,但没有运气。

    这个问题试图获得与 this one ,但我在问我的事件处理宏中可能做错了什么。

    1 回复  |  直到 15 年前
        1
  •  4
  •   Julien Poulin    15 年前

    问题是,当事件触发时,文档实际上不是活动的。一种解决方案是在发生documentopened事件后,使用“fire once”计时器在短时间内执行代码:

    Dim DocumentOpenedTimer As Timer
    
    Private Sub DocumentEvents_DocumentOpened(ByVal Document As EnvDTE.Document) Handles DocumentEvents.DocumentOpened
        DocumentOpenedTimer = New Timer(AddressOf ExpandRegionsCallBack, Nothing, 200, Timeout.Infinite)
    End Sub
    
    Private Sub ExpandRegionsCallBack(ByVal state As Object)
        ExpandRegions()
        DocumentOpenedTimer.Dispose()
    End Sub
    
    Public Sub ExpandRegions()
        Dim Document As EnvDTE.Document = DTE.ActiveDocument
        If (Document.FullName.EndsWith(".vb") OrElse Document.FullName.EndsWith(".cs")) Then
            If Not DTE.ActiveWindow.Caption.ToUpperInvariant.Contains("design".ToUpperInvariant) Then
                Document.DTE.SuppressUI = True
                Document.DTE.ExecuteCommand("Edit.CollapsetoDefinitions")
                Dim objSelection As TextSelection = Document.Selection
                objSelection.StartOfDocument()
                Do While objSelection.FindText("#region", vsFindOptions.vsFindOptionsMatchInHiddenText)
                Loop
                objSelection.StartOfDocument()
                Document.DTE.SuppressUI = False
            End If
        End If
    End Sub
    

    我没有广泛测试过,所以可能有一些错误…此外,我还添加了一个检查,以验证活动文档是否是C或VB源代码(尽管没有用VB进行测试),以及它是否处于设计模式。
    不管怎样,希望它对你有用…