如何创建可用的表单实例?

How do I create a usable form instance?

我试过创建表单实例,但 none 成功了。

此代码有效并打开和关闭 "lamp":

Public Class Lamp
    ' declare field
    Private lampColor As Color

    Public Sub New()
        ' initialize field
        lampColor = MainForm.lampShape.FillColor
    End Sub ' New

    Public Sub Switch()
        ' determine if lamp is on or off
        If lampColor = Color.Silver Then
            ' turn on lamp
            lampColor = Color.Yellow
        Else
            ' turn off lamp
            lampColor = Color.Silver
        End If

        ' display color on lamp
        MainForm.lampShape.FillColor = lampColor
    End Sub ' Switch
End Class

此代码无效:

Public Class Lamp
    ' declare fields
    Private lampColor As Color
    Private main As New MainForm

    Public Sub New()
        ' initialize field
        lampColor = main.lampShape.FillColor
    End Sub ' New

    Public Sub Switch()
        ' determine if lamp is on or off
        If lampColor = Color.Silver Then
            ' turn on lamp
            lampColor = Color.Yellow
        Else
            ' turn off lamp
            lampColor = Color.Silver
        End If
        ' display color on lamp
        main.lampShape.FillColor = lampColor
   End Sub ' Switch
End Class

我也在许多其他项目中尝试过此方法,其中 none 有效。

因为你的 class 从来没有显示它创建的主要内容,但你说你可以看到 "square" 没有改变颜色,你很可能有 2 个正在使用的表单实例: VB 应用程序框架创建为 Startup 表单,然后是您在 Lamp class 中创建的表单。将 main.Show() 添加到您的构造函数(sub New),我敢打赌您会看到第二种形式。

来自评论:

After I did that, two forms are now opened

关键字New创建了一个新对象。因此,虽然您的第二个 class 确实使用了表单实例,但它创建了自己的 New 实例,这与 VB 创建和显示的实例不同。


假设该表单是应用程序的主表单,并且该表单创建了 class,这就是您想要的:

Public Class Lamp
    Private lampColor As Color
    Private main As MainForm           ' no New!

    Public Sub New(frm As MainForm)
        main = frm                     ' store reference to the form passed

        lampColor = main.lampShape.FillColor
    End Sub ' New
    ...

然后当你创建它时:

Public Class MainForm
   Private myLamp As Lamp            ' just declare it
   ...
   ' in form load:
       myLamp = New Lamp(Me)             ' pass this form inst to the lamp object