Visual Basic 2010中与VB6的Picture1.Cls功能等效的代码是什么?
问题:VB2010中实现VB6的Picture1.Cls等效功能,解决PictureBox条码不更新问题
在条码应用项目中,需要每次修改TextBox内容(删除/添加字符串)时,根据当前内容重新生成条码,但修改文本后旧条码依然保留,尝试过PictureBox1.Invalidate()、PictureBox1.Refresh()和重置temp为0都没用。代码如下:
Private Sub make39() '...省略其他代码... 'PictureBox1.Invalidate() 'PictureBox1.Refresh() If TextBox1.Text = "" Then Exit Sub pos = 5 Bardata = UCase(TextBox1.Text) temp = BC(43) & "0" & temp & BC(43) 'Generate Barcode For x = 1 To Len(temp) If x Mod 2 = 0 Then 'SPACE pos = pos + 1 + (2 * Val(Mid$(temp, x, 1))) + 1 Else 'BAR For y = 1 To 1 + (2 * Val(Mid$(temp, x, 1))) ga = PictureBox1.CreateGraphics ga.DrawLine(Pens.Black, pos, 1, pos, 58 - 1 * 8) pos = pos + 1 Next End If Next ga.DrawString(TextBox1.Text, New System.Drawing.Font("Microsoft Sans Serif", 10), Brushes.Red, New System.Drawing.Point(90 + Len(Bardata) * (5 + 1 * 2), 55)) temp = 0 End Sub
解决方法
1. VB6的Picture1.Cls等效实现
VB2010中没有直接的Cls方法,但可以通过两种方式实现清除PictureBox内容:
- 方法一:直接重置Image属性
PictureBox1.Image = Nothing - 方法二:创建空白图像覆盖原有内容(保留背景色)
Using bmp As New Bitmap(PictureBox1.Width, PictureBox1.Height) Using g As Graphics = Graphics.FromImage(bmp) g.Clear(PictureBox1.BackColor) End Using PictureBox1.Image = bmp End Using
2. 修正绘制逻辑(关键)
你当前用PictureBox1.CreateGraphics绘制的内容是临时的,且不会自动清除旧内容。正确的做法是先清除原有图像,在独立画布上绘制新条码,再赋值给PictureBox的Image属性:
修改后的make39示例:
Private Sub make39() '先清除原有内容 PictureBox1.Image = Nothing If TextBox1.Text = "" Then Exit Sub pos = 5 Bardata = UCase(TextBox1.Text) temp = BC(43) & "0" & temp & BC(43) '创建新位图作为绘制画布 Using bmp As New Bitmap(PictureBox1.Width, PictureBox1.Height) Using ga As Graphics = Graphics.FromImage(bmp) '填充背景色,彻底清除残留 ga.Clear(PictureBox1.BackColor) '生成条码 For x = 1 To Len(temp) If x Mod 2 = 0 Then '处理空白区域 pos = pos + 1 + (2 * Val(Mid$(temp, x, 1))) + 1 Else '绘制条码竖线 For y = 1 To 1 + (2 * Val(Mid$(temp, x, 1))) ga.DrawLine(Pens.Black, pos, 1, pos, 58 - 1 * 8) pos = pos + 1 Next End If Next '绘制条码文本 ga.DrawString(TextBox1.Text, New System.Drawing.Font("Microsoft Sans Serif", 10), Brushes.Red, New System.Drawing.Point(90 + Len(Bardata) * (5 + 1 * 2), 55)) End Using '将绘制好的位图赋值给PictureBox PictureBox1.Image = bmp End Using temp = 0 End Sub
3. 触发更新的时机
在TextBox内容变化事件中调用make39,确保每次修改文本都自动更新条码:
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged make39() End Sub
内容的提问来源于stack exchange,提问作者afkaar
相关产品推荐
相关产品推荐

