在类中对Form作一些控件上的增减,并需要增加的控件都响应事件
''Class1.cls''定义
Private frm As Form
Private WithEvents lblAdvance As LabelPublic Sub InitData()
Set frm = Form1 Set lblAdvance = frm.Controls.Add("VB.Label", "lblAdvance")
lblAdvance.Move 4590, 1950, 780, 195
lblAdvance.BackStyle = 0 'Transport
lblAdvance.ForeColor = vbBlue
lblAdvance.FontUnderline = True
lblAdvance.MousePointer = vbCustom
lblAdvance.MouseIcon = LoadResPicture(101, vbResCursor) ''光标也没发生变化哦
lblAdvance.Caption = "高级模式"
lblAdvance.Visible = True
End Sub''Label 单击事件
Private Sub lblAdvance_Click()
MsgBox "Click"
End Sub这样动产生的事件,鼠标点击Label时没有反应,而且光标也没有变化,这个要怎么解决?
''Class1.cls''定义
Private frm As Form
Private WithEvents lblAdvance As LabelPublic Sub InitData()
Set frm = Form1 Set lblAdvance = frm.Controls.Add("VB.Label", "lblAdvance")
lblAdvance.Move 4590, 1950, 780, 195
lblAdvance.BackStyle = 0 'Transport
lblAdvance.ForeColor = vbBlue
lblAdvance.FontUnderline = True
lblAdvance.MousePointer = vbCustom
lblAdvance.MouseIcon = LoadResPicture(101, vbResCursor) ''光标也没发生变化哦
lblAdvance.Caption = "高级模式"
lblAdvance.Visible = True
End Sub''Label 单击事件
Private Sub lblAdvance_Click()
MsgBox "Click"
End Sub这样动产生的事件,鼠标点击Label时没有反应,而且光标也没有变化,这个要怎么解决?
肯定过早地释放了该实例,应该和 Form1 的生命周期同步。
'Form1
Option ExplicitPrivate c1 As Project1.Class1Private Sub Form_Load()
Set c1 = New Class1
c1.InitData
End SubPrivate Sub Form_Unload(Cancel As Integer)
Set c1 = Nothing
End Sub
'Dim A As New Class1 而不能放在这里
Set A = New Class1'创建类对象
A.InitData
End SubPrivate Sub Form_Unload(Cancel As Integer)
Set A = Nothing
End Sub类里面的代码我一个字也没改,只是声明的位置不一样,放在最上面,全局的位置就有反应,放在Load事件里面就没有反应。因为如果放在Load事件里,随着Load事件的结束,类对象A就会被释放,所以就没有反应了
加入下面两句调试,看输出
'Form1
Private Sub Form_Load()
Debug.Print Now, "Form_Load()", Hex(Me.hWnd)
'''
End Sub
'Class1.cls
Public Sub InitData()
Debug.Print Now, "InitData()", Hex(Form1.hWnd)
...
End Sub
将
Private frm As Form
改为
Private withevents frm As Form
即可这样 frm 就与Form中完全一样相应事件了。
将
Set lblAdvance = frm.Controls.Add("VB.Label", "lblAdvance")
改为
Set lblAdvance = frm.Controls.Add("VB.Label", "lblAdvance",frm)这样就响应时间了。