2009-06-26 103 views
1

我在Visual Studio 2008中工作,我希望在打开文件时运行Edit> Outlining> Collapse to Definitions来运行。如果在此之后所有地区都扩大了,那将会很好。我尝试了Kyralessa在关于The Problem with Code Folding的评论中提供的代码,并且该代码非常适合作为必须手动运行的宏。我试图通过将以下代码EnvironmentEvents模块在宏IDE扩展这个宏作为一个事件:EnvironmentEvent宏没有完成

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 

然而,这似乎并没有当我从我的解决方案打开一个文件做任何事VS.为了测试这个宏是否正在运行,我在该子程序中输入了MsgBox()语句,并注意到Document.DTE.ExecuteCommand("Edit.CollapsetoDefinitions")之前的代码运行正常,但在该行之后似乎没有任何结果。当我在子例程中调试并设置了一个断点时,我会按F10继续下一行,一旦ExecuteCommand行运行,控件就会离开子例程。尽管如此,这条线似乎什么也不做,即它不会折叠轮廓。

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

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

回答

4

问题在于事件触发时文档不是真正活动的。一个解决方案是使用“火一次”计时器来执行代码的DocumentOpened事件之后的短暂延迟发生:

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进行测试),并且它不处于设计模式。
无论如何,希望它适用于你...

+0

圣洁的废话,它的作品!我不得不在我的EnvironmentEvents宏中为`Timer`和`Timeout`添加一个`Imports System.Threading`行,但它起作用!我现在打开我的CS文件,大约一秒之后,我的所有定义都崩溃了。谢谢! – 2009-07-10 13:52:11