Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleGet an object's reference count in Visual Basic 6
DescriptionThis example shows how to get an object's reference count in Visual Basic 6.
Keywordsreference count, get reference count, Visual Basic 6
CategoriesAPI, Miscellany
 
The GetRefCount function looks at the memory address 4 bytes after an object reference's address and copies the long integer value there. It subtracts 3 to adjust for extra references added by the call to the function.
 
Private Declare Sub CopyMemory Lib "kernel32" Alias _
    "RtlMoveMemory" (dest As Any, src As Any, ByVal nbytes _
    As Long)

' Return the number of references to the object.
' We subtract 3 to adjust for references made by parameters.
Private Function GetRefCount(ByRef obj As IUnknown) As Long
    If obj Is Nothing Then Exit Function
    CopyMemory GetRefCount, ByVal (ObjPtr(obj)) + 4, 4
    GetRefCount = GetRefCount - 3
End Function
 
The program makes a collection containing a reference to a form. The Add Reference button adds a new reference to that same object. The Remove Reference button removes a reference.

As the program adds and removes references, it displays the number of references to that object and the number of items in the collection (they should match).

 
Private References As Collection

' Make a Form1 instance to have references to.
Private Sub Form_Load()
    Set References = New Collection
    References.Add New Form1

    lblResults.Caption = GetRefCount(References(1)) & " " & _
        "references"
    lblNumItems.Caption = References.count & " items"
End Sub

' Add a new reference.
Private Sub cmdAddReference_Click()
    References.Add References(1)
    lblResults.Caption = GetRefCount(References(1)) & " " & _
        "references"
    lblNumItems.Caption = References.count & " items"
    cmdRemoveReference.Enabled = True
End Sub

' Delete a reference.
Private Sub cmdRemoveReference_Click()
    References.Remove References.count
    lblResults.Caption = GetRefCount(References(1)) & " " & _
        "references"
    lblNumItems.Caption = References.count & " items"
    cmdRemoveReference.Enabled = (References.count > 1)
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated