如何检查用于访问当前表单的表单?

时间:2016-02-27 08:50:43

标签: vb.net

我有3种形式,即Form1Form2& Form3

Form1Form2都可以访问Form3。但是,我要为Form3中的按钮提供不同功能取决于使用哪种表单来访问Form3

有人可以自由地向我解释如何编码应该有效吗?此外,如果你们有这个问题之前回答的链接或更好的概念,我将非常感激。提前谢谢。

我粗略的想法

Public Class Form3
   Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
      If 'user are access from Form1 Then
           'Action if user are access from Form1 here
      Else
           'Action if user are access from Form2 here
      End If
   End Sub
End Class

2 个答案:

答案 0 :(得分:2)

此代码的问题

If Me.Owner.Equals(Form1) Then . . . 

这种方式你有紧密耦合的对象 - Form2和1知道Form3和Form3知道2和1.它可能不是你或现在的问题。但是在OOP中这是一个问题,将来它可能是您的对象可伸缩性的问题。这是OOP方法。从我的脑袋写,所以可能存在语法错误的项目:

Public Interface IFormCanDoSomething
    Sub DoSomething()
    ReadOnly Property FormAction As EnumFormActions 
End Interface

Public Class Form1
    Implements IFormCanDoSomething

    ReadOnly Property FormAction As EnumFormActions Implements IFormCanDoSomething.FormAction
        Get
            Return EnumFormActions.Action1
        End Get
    End Property

    Sub DoSomething() Implements IFormCanDoSomething.DoSomething
        Dim f As New Form3(Me)
        f.Show()
    End Sub
End Class

Public Class Form2
    Implements IFormCanDoSomething

    ReadOnly Property FormAction As EnumFormActions Implements IFormCanDoSomething.FormAction
        Get
            Return EnumFormActions.Action2
        End Get
    End Property

    Sub DoSomething() Implements IFormCanDoSomething.DoSomething
        Dim f As New Form3(Me)
        f.Show()
    End Sub
End Class   


Public Class Form3

    Private _owner As IFormCanDoSomething
    Public Sub New(owner As IFormCanDoSomething)
        _owner = owner
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If _owner.FormAction = EnumFormActions.Action1 Then
           'Action if user needs one thing
        ElseIf  _owner.FormAction = EnumFormActions.Action2 Then
           'Action if user needs another thing  here
        ElseIf  _owner.FormAction = EnumFormActions.Action3 Then
           'Action if user needs third thing
        End If

    End Sub
End Class

那么这里的收益是多少?看Button1_Click。你有看到? - 现在你可以有许多Form3需要执行Action1的表单,或/和Form3需要执行Action2的许多表单等等。这可能会更进一步,但现在还不够好

答案 1 :(得分:1)

假设您正在使用Show方法,请将表单作为所有者传递给它:

Form3.Show(Form1)

然后引用Form3所有者:

Public Class Form3
   Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If Me.Owner.Equals(Form1) Then
            'Action if user are access from Form1 here
    ElseIf Me.Owner.Equals(Form2) Then
            'Action if user are access from Form2 here
    End If
   End Sub
End Class