views:

498

answers:

4

In some VB6 code, I have a handler for a TreeView's Collapse event:

Private Sub MyTree_Collapse(ByVal Node as MSComCtlLib.Node)

This is called whenever a node in the tree is collapsed, whether by the user or programmatically. As it turns out, through some roundabout execution, it may happen that this handler will wind up telling a node to collapse, leading to infinite recursion.

I can think of multiple ways to skin this cat, but what seems simplest to me is to tell the TreeView not to raise events for some period of time. I can't find a simple call to let me do this, though. Has anyone successfully done this, or do I need to keep track of state in some other manner so I can respond appropriately when recursive events come along?

+1  A: 

I think that like many events in VB, it can't be switched off.

Just set a boolean flag as you've suggested.

Phil Bachmann
+2  A: 

@Phil - I came to the same conclusion. My implementation of MyTree_Collapse now looks something like this (where m_bHandlingCallback is a member variable):

Private Sub MyTree_Collapse(ByVal Node as MSComCtlLib.Node)
    If m_bHandlingCallback Then Exit Sub

    m_bHandlingCallback = True
    DoSomeStuff
    m_bHandlingCallback = False
End Sub
Matt Dillard
A: 

I would declare the flag variable as STATIC in the Sub. This avoids making the variable global and makes it keep its value between calls.

Jonathan Swift
Is a function static variable in VB shared across all instances of a class, like it is in C++? I went with member data (not global data) so that setting the flag wouldn't affect _all_ instances of my class - just the one I cared about.
Matt Dillard
+2  A: 

Another way in VB6 is to have an alternate WithEvents reference to the control:

Private WithEvents alt as TreeView

and in Form_Load:

Private Sub Form_Load()
Set alt = MyTree
End Sub

Now alt will receive lots of events like this:

Private Sub alt_Collapse(ByVal Node as MSComCtlLib.Node)
Set alt = Nothing
'DoSomeStuff'
Set alt = MyTree
End Sub

But, during the DoSomeStuff, the events are unhooked - which also applies to all other event Subs for alt without the need for them to have intrusive changes.

quamrana