Get the form which calls some code in a class???

  • Thread starter Thread starter Alex Stevens
  • Start date Start date
A

Alex Stevens

Hi all.

I have a class which performs some tasks for which ever form it get s bound
to using a bindForm methods which accepts a form object.
I'd like to do away with this method as it only ever gets used like this:

BindForm(Me)

Is there anyway, that I can get the form object in the class, when it is
instatianted by the form?
In other words I'd like to be able to get the object that is calling the
code, within the actual code.
It would be a Sender type object.....?

Thanks

Alex
 
Alex Stevens said:
I have a class which performs some tasks for which ever form it get s
bound to using a bindForm methods which accepts a form object.
I'd like to do away with this method as it only ever gets used like
this:

BindForm(Me)

Is there anyway, that I can get the form object in the class, when it
is instatianted by the form?
In other words I'd like to be able to get the object that is calling
the code, within the actual code.
It would be a Sender type object.....?

I don't think it is possible, and if it was possible, I would call it bad
design. Why don't you want to pass the form object? Or, why don't you put
the procedure into the form class? If it is not possible because different
form types need to be passed, why don't you derive all forms from a base
form containing the procedure?
 
Hi Alex,

Like Armin, I think it's highly dubious. But I'm curious about your
objection to passing in the Form and I'd like to know what it's all about
too!!

If you insist on doing it then I can tell you that this <is> a way. After
all, when you look at a stack trace, it shows the hierarchy of methods and
their parameters and values. The Form that you require would be the main
parameter of the calling method.

System.Diagnostics has a whole load of stuff for querying the stack. You
can easily determine the class of the calling Form but it's probably a lot of
work to get the actual Form object via this route.

Try the following:

Public Function MeAndMyCaller As String
Dim CurrentStack As New System.Diagnostics.StackTrace
Dim Myself As String = CurrentStack.GetFrame(0).GetMethod.Name
Dim MyCaller As String = CurrentStack.GetFrame(1).GetMethod.Name
Dim CallersFrame As StackFrame = CurrentStack.GetFrame(1)
Dim CallerType As Type = CallersFrame.GetMethod.ReflectedType
Dim S As String = CurrentStack.ToString & vbCrLf & vbCrLf
S = S & "In: " & Myself & vbCrLf _
& "Called by: " & MyCaller & vbCrLf _
& "Caller Type: " & CallerType.ToString
MsgBox (S)
End Function

You'll see that you can get names and types but getting object references
is going to take more investigation.

Do tell us what it's about. :-)

Regards,
Fergus
 
Back
Top