Windows Form动态添加PictureBox不显示,寻求技术解决建议
解决PictureBox无法显示的问题
嘿,我一眼就揪出问题所在了——你成功创建了PictureBox实例并把它们存入了List,但这些控件从来没有被添加到窗体的控件集合中,Windows Forms根本不知道要渲染它们!下面是具体的解决步骤和优化建议:
核心修复:将PictureBox添加到窗体控件集合
在newqueuemember()方法里,创建完PictureBox并设置好属性后,一定要加上这行代码:
Me.Controls.Add(pictureBox)
这行代码相当于告诉窗体:“把这个控件加入我的渲染列表,显示出来!”
避免控件重叠(可选但关键)
你现在把所有PictureBox的位置都设为New Point(10, 20),它们会完全重叠在一起,看起来就像只有一个控件存在。可以利用List的计数来动态设置位置,让每个新成员排列开:
' 每个新控件往右偏移60像素(50宽度+10间距) pictureBox.Location = New Point(10 + peoples.Count * 60, 20)
优化随机数生成(推荐)
你当前使用的Rnd()和Randomize()是VB6时代的旧方法,在Timer高频触发的场景下容易生成重复值。建议改用.NET的Random类,更稳定可靠:
- 在类级别声明一个Random实例:
Dim rng As New Random()
- 修改你的随机数函数:
Function randomnumber(lower As Integer, upper As Integer) As Integer ' Next方法是[lower, upper),所以要+1来包含upper Return rng.Next(lower, upper + 1) End Function
修改后的完整代码
Public Class Form1 Dim peoples As New List(Of PictureBox)() Dim rng As New Random() ' 类级别的随机数实例 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Timer1.Enabled = True Timer1.Interval = randomnumber(100, 500) End Sub Sub loopover() Timer1.Interval = randomnumber(100, 500) End Sub Function randomnumber(lower As Integer, upper As Integer) As Integer Return rng.Next(lower, upper + 1) End Function Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick loopover() newqueuemember() End Sub Private Sub newqueuemember() Dim pictureBox As New PictureBox pictureBox.Width = 50 pictureBox.Visible = True pictureBox.Height = 50 Dim selectperson As Integer = randomnumber(1, 3) If selectperson = 1 Then pictureBox.Image = My.Resources.person1 ElseIf selectperson = 2 Then pictureBox.Image = My.Resources.person2 Else pictureBox.Image = My.Resources.person3 End If ' 动态设置位置,避免重叠 pictureBox.Location = New Point(10 + peoples.Count * 60, 20) ' 将控件添加到窗体 Me.Controls.Add(pictureBox) peoples.Add(pictureBox) End Sub End Class
现在运行代码,你应该能看到一个个PictureBox依次显示在窗体上了!
内容的提问来源于stack exchange,提问作者Luke Horner-Long
相关产品推荐
相关产品推荐

