Listening for Events from a Runtime Control

I created a class that, when providing UserForm as an argument, should put the control in this user form and listen for its events.

Simplified class:

eventsTestItem the class

Private WithEvents formControl As MSForms.Image
Private parentUF As MSForms.UserForm

Private Sub formControl_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
MsgBox "clicked"
End Sub

Public Property Let Visible(ByVal makeVisible As Boolean)
    '(make) and show if true, otherwise delete
    If makeVisible Then
        ImageBase.Visible = True
    Else
        ParentForm.Controls.Remove ImageBase.Name
    End If
End Property

Public Property Set ItemParentUF(ByVal value As MSForms.UserForm)
    Set parentUF = value
End Property

Private Property Get ParentForm() As MSForms.UserForm
    If parentUF Is Nothing Then
        Err.Description = "Grid Item Requires parent Form to be set"
        Err.Raise 5                              'no parent uf set yet
    Else
        Set ParentForm = parentUF
    End If
End Property

Public Property Get ImageBase() As MSForms.Image
    If formControl Is Nothing Then
        Set formControl = ParentForm.Controls.Add("Forms.Image.1", Name:="TestImage", Visible:=False)
    End If
    Set ImageBase = formControl
End Property

Public Property Set ImageBase(value As MSForms.Image)
    Set formControl = value
End Property

which I expect to make a control Imagewhose events I can customize.

To test, I created an empty user form with the following code:

Private Sub UserForm_Initialize()

    Dim testItem As New eventsTestItem  'create event listener class
    With testItem
        Set .ItemParentUF = Me   'tell it which userform to create a new control on
        .Visible = True     'Make and display the control
    End With
    Debug.Assert Me.Controls.Count = 1 'check if control added

End Sub

It is executed without errors (i.e. a control is created, it is also displayed on the form).

But the event listener does not work as expected, the event should be raised when I click on the image. What am I missing here?

+4
source share
2 answers

testItem UserForm_Initialize.

, . , Static :

Private Sub UserForm_Click()
    Static testItem As Class1

    Set testItem = New Class1  'create event listener class
    With testItem
        Set .ItemParentUF = Me   'tell it which userform to create a new control on
        .Visible = True     'Make and display the control
    End With
    Debug.Assert Me.Controls.Count = 1 'check if control added

End Sub
+2

, testItem , .

Private Sub UserForm_Initialize()

    Dim testItem As New eventsTestItem  'procedure-scoped
    '...

End Sub

, .

+2

Source: https://habr.com/ru/post/1695432/


All Articles