How to get reference to the Calling Form from func

2019-08-23 14:49发布

问题:

I have two projects. One is GUI, and the second is DLL.

I Call a function In DLL from Form1

The DLL function has to interface the form (Say, Change Back Color)

I would like to get the Calling form as a reference, without passing as parameter.

Here is Example from Form 1

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ChangeBackColor()
End Sub

DLL function

Public Sub ChangeBackColor()
  Dim CallingForm as Form
  '''GET PARENT HERE'''
  CallingForm.BackColor = Color.Cyan
End Sub

Obviously, I can do this if I pass Form every time, But trying to avoid that. Thank in advance

Someone Noted this question has been answered elsewhere. It has not been answered (or asked) as far as I could see. This is specific to Referencing a Form, not a method or other Object.

I have gotten the solution to reference the calling form, by referencing Form.ActiveForm And am now answering my own question below.

回答1:

From a design perspective this is really a bad thing to want.

Designing your application this way has a number of serious problems:

  • You're relying on something like an ambient context, which is a anti pattern if used incorrectly. And this is a typical case of incorrect use because of:
  • you're hiding the fact that ChangeBackColor function is dependent on a form calling the method!! What if some other code block is calling this code? The code will fail!!

The last point is especially a problem because this makes unit testing this piece of code extremely hard and error prone. Methods signatures are all about communicating the intend of the function and thereby also needs to tell which things (objects, values, services etc.) it needs to perform the work.

So if the form or whatever object is needed in the function show in it in the signature!!

If you don't like the fact that you need to add this in every call, you could prettify the code by creating it as an extension method:

Public Module FormExtensions
   <Extension>
   Public Sub ChangeBackColor(form as Form, newBackColor as Color)
        form.Backcolor = newBackColor
   End Sub
End Module

which you call like this in your form instance:

Me.ChangeBackColor(Color.Red)


回答2:

I ended up calling the active form by using

Form.ActiveForm

The following Function works now (along with others)

Public Sub ChangeBackColor()
  Dim CallingForm as Form
  '''GET PARENT HERE'''
  CallingForm = Form.ActiveForm
  CallingForm.BackColor = Color.Cyan
End Sub

Thank you everyone who tried helping



标签: c# vb.net dll