问题是,当事件触发时,文档实际上不是活动的。一种解决方案是在发生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进行测试),以及它是否处于设计模式。
不管怎样,希望它对你有用…