"已经与其基础RCW分离的COM对象无法使用"与vb.net表单事件相关的错误

时间:2017-07-07 12:13:17

标签: vb.net events com arcobjects rcw

我将arcobjects地图事件挂钩到vb.net表单以侦听地图选择更改。这一切都很好,但用户在打开表单时偶尔会报告此错误。我无法看到任何模式来重现错误,它似乎是随机的。

"已与基础RCW分离的COM对象无法使用"

它源自 Load()方法,我挂钩事件。

有谁能帮我理解我做错了什么?我在FormClosing()事件中取消了地图选择事件,我认为这是正确的方法。

Public Class MyForm

    Private _activeViewEvents As IActiveViewEvents_Event

    Private Sub FormLoad(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        _activeViewEvents = TryCast(pMxDoc.ActiveView.FocusMap, IActiveViewEvents_Event)
        AddHandler _activeViewEvents.SelectionChanged, AddressOf SelectionChanged    
    End Sub

    Private Sub SelectionChanged
        'do something when selection is changed
    End Sub

    Private Sub FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
        RemoveHandler _activeViewEvents.SelectionChanged, AddressOf SelectionChanged
    End Sub

End Class

2 个答案:

答案 0 :(得分:1)

您创建和销毁处理程序的方法是有效的。在表单打开时更改地图文档时,您可以收到RCW COM异常。由于您使用FocusMap创建句柄,因此在更改文档时,FocusMap也是如此,这意味着您需要为新地图文档重新创建处理程序。

答案 1 :(得分:0)

好的,我想我已经通过使用ActiveViewChanged事件解决了这个问题。我没有在每个表单加载或新文档事件上重新加入事件,而是尝试在每次触发ActiveViewChanged事件时重新调用SelectionChanged事件。事实证明,每次打开新文档时都会多次触发(不确定原因)。无论如何,问题似乎已经消失。这是一些示例代码:

Public Class MyForm

Private _activeViewEvents As IActiveViewEvents_Event
Private _docEvents As IDocumentEvents_Event

Private Sub FormLoad(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    AddHandler _docEvents.ActiveViewChanged, AddressOf ActiveViewChanged
End Sub

Private Sub ActiveViewChanged()
    Dim maps = pMxDoc.Maps
    For i = 0 to maps.Count - 1 'remove handlers from all maps
        RemoveActiveViewEvents(maps.Item(i))
    Next
    SetupActiveViewEvent(pMxDoc.ActiveView.FocusMap) 'only add handler to active map
End Sub

Private Sub RemoveActiveViewEvents(map As IMap)
    _activeViewEvents = CType(map, IActiveViewEvents_Event)
    RemoveHandler _activeViewEvents.SelectionChanged, AddressOf SelectionChanged
End Sub

Private Sub SetupActiveViewEvents(map As IMap)
    _activeViewEvents = CType(map, IActiveViewEvents_Event)
    AddHandler _activeViewEvents.SelectionChanged, AddressOf SelectionChanged
End Sub

Private Sub SelectionChanged
    'do something when selection is changed
End Sub

End Class