Form_KeyPress in Class
Form1.frm
Private Sub Form_Load()
Call myFunction
End Sub
Private Sub myFunction()
Dim c as New MyClass
Call c.AddControl(Me)
End Sub
MyClass.cls
Dim WithEvents oForm As Form
Public Sub AddControl(ByRef objForm As Form)
Set oForm = objForm
oForm.KeyPreview = True '' for KeyPress Event
End Sub
Private Sub oTestForm_KeyPress(KeyAscii As Integer)
Debug.Print KeyAscii
End Sub
I like to fire oTestForm_KeyPress event but I dont want to write this event in Form1.frm. How can I make it work?
Any Idea would be appreciated.
Thanks.
[655 byte] By [
Sync] at [2007-11-11 8:18:07]

# 1 Re: Form_KeyPress in Class
I don't think you can; in VB6, event handlers must be in the form whose events they handle. The best you can do is have the Form_KeyPress event procedure in the form call a public method of your class.
# 2 Re: Form_KeyPress in Class
There are two problems:
1) error is in the line:
Private Sub oTestForm_KeyPress(KeyAscii As Integer)
that musy be
Private Sub oForm_KeyPress(KeyAscii As Integer)
2) you declared an instance of MyClass (c) inside the Load event, therefore it goes out of scope as soon as the Load event ends. You must declare it static (outside the Load event) like
private c as MyClass
private Form_Load()
set c = new MyClass
...
@Phil: in VB this is a very common tecnique, to "delegate" a class to listen to event, to make the form less crowded. unfortunarelly it creates circolar reference problems, and cannot be used in AciveX projects
Marco
mstraf at 2007-11-11 17:26:38 >

# 3 Re: Form_KeyPress in Class
Thank you so much. mstraf and Phil Weber. :-)
Form1.frm
Dim c as New MyClass
Private Sub Form_Load()
Call myFunction
End Sub
Private Sub myFunction()
Set c = New MyClass
Call c.AddControl(Me)
End Sub
MyClass.cls
Dim WithEvents oForm As Form
Public Sub AddControl(ByRef objForm As Form)
Set oForm = objForm
oForm.KeyPreview = True '' for KeyPress Event
End Sub
Public Sub oForm_KeyPress(KeyAscii As Integer)
Debug.Print KeyAscii
End Sub
Sync at 2007-11-11 17:27:49 >
