0

我正在创建一个类,每次调用“New”时都会创建一个已经存在的表单的新实例。我在类库中实现这个,类库有一个“WndClass”(类)和一个“MainWindow”(窗体)。问题是每当我尝试通过 InsWindow.Close 关闭窗口时都会出现上述错误

这是代码:

Public Class WndClass
   Public Shared WindowCount As Integer
   Private InsWindow As MainWindow

Public Sub New()
    WindowCount += 1
    InsWindow = New MainWindow
    InsWindow.Show()
End Sub

'.... Some window manipulation functions

Protected Overrides Sub Finalize()
    WindowCount -= 1
    InsWindow.Close()
    InsWindow.Dispose()
    MyBase.Finalize()
End Sub
End Class

我对这门语言还很陌生,所以我决定去试验和编码我想到的随机想法。

编辑:我已经阅读了一些类似但不一定相同的问题,其中一些人说代表是解决问题的原因,有人可以解释我如何使用它来解决这个问题吗?

4

1 回答 1

0

Without knowing the error, I can only take a shot in the dark...

The fact that you mentioned delegates, I would recommend trying the following:

Protected Overrides Sub Finalize()

    If Me.InvokeRequired Then
        Me.Invoke(New MethodInvoker(AddressOf Me.Finalize))
    Else
        WindowCount -= 1
        InsWindow.Close()
        InsWindow.Dispose()
        MyBase.Finalize()
    End If

End Sub

Delegates are used when you need to change the thread that the code is running on (ie: you need to get back to the UI thread).

Normally you'd have to create a delegate (ie: Private Delegate Sub Test(val1 As String, val2 As String, etc..)) then invoke the delegate while passing it the address of the method you wish to invoke (Note: the variables of the delegate must match the method being called).

If there are no variables being passed to the method, you can invoke the MethodInvoker like so Me.Invoke(New MethodInvoker(AddressOf Me.Foo))...

Keep in mind it's good practice to always check if an invoke is required by checking Me.InvokeRequired

于 2013-10-23T10:48:02.893 回答