我正在尝试在for循环中创建图片框,然后将它们添加到我的主窗体中。我在另一个线程中创建了图片框以减少加载时间,但我的应用程序一直反复崩溃。
我将代码更改了10次,实际版本看起来像这样。
Private letters() As PictureBox
Private Sub loadLetters()
Dim j As Integer = 0
letters = New PictureBox() {}
For value As Integer = 0 To 7
letters(value).Image = ImageList1.Images(value + 8)
letters(value).Name = "picLetter_" & value + 8
letters(value).Location = New Point(0, j)
letters(value).Size = New Size(100, 100)
letters(value).Visible = True
j = j + 100
Me.BeginInvoke(New MethodInvoker(AddressOf loadLetters))
Next
End Sub
我的另一次尝试让我想到了这一点:
If Me.InvokeRequired Then
Dim d As New updateMain(AddressOf loadLetters)
Me.Invoke(d, New Object() {letters(value)})
Else
Me.Controls.Add(letters(value))
End If
Private Delegate Sub updateMain(ByVal picture As PictureBox)
如何从另一个帖子中将图片框添加到主表单?
答案 0 :(得分:0)
您继续调用相同的方法,这意味着每次调用时都会尝试创建另外八个图片框。由于您正在尝试创建无限量的图片框,因此常量和连续调用最终会导致StackOverflow
异常。
您必须创建一个单独的方法来添加图片框 ,让您的主方法创建它们,并使用单独的方法将它们添加到表单中。
Private Delegate Sub AddPictureBoxDelegate(ByRef PBox As PictureBox)
'ByRef is better to use when not creating a copy of the PictureBox (and when you're not going to modify it as a separate one).
Private Sub AddPictureBox(ByRef PBox As PictureBox)
If Me.InvokeRequired = True Then 'Invocation is required.
'Call the method again, using invocation.
Me.Invoke(New AddPictureBoxDelegate(AddressOf AddPictureBox), PBox)
Else 'No (further) invocation required.
Me.Controls.Add(PBox)
End If
End Sub
现在,在您的主题中,您只需致电:
AddPictureBox(letters(value))
一切都应该按预期工作。