我有一些代码可以通过将控件后面的每个控件绘制到它的背景上来为控件创建“适当的”透明度。
使用方法:
1) 创建一个自定义类。 (从“添加新项目”菜单)
2) 给它一个您选择的名称(例如:TransparentPictureBox)
3) 使其继承自原始的 PictureBox。
Public Class TransparentPictureBox
Inherits PictureBox
End Class
4) 将此代码粘贴到类中:
Protected Overrides Sub OnPaintBackground(e As System.Windows.Forms.PaintEventArgs)
MyBase.OnPaintBackground(e)
If Parent IsNot Nothing Then
Dim index As Integer = Parent.Controls.GetChildIndex(Me)
For i As Integer = Parent.Controls.Count - 1 To index + 1 Step -1
Dim c As Control = Parent.Controls(i)
If c.Bounds.IntersectsWith(Bounds) AndAlso c.Visible = True Then
Dim bmp As New Bitmap(c.Width, c.Height, e.Graphics)
c.DrawToBitmap(bmp, c.ClientRectangle)
e.Graphics.TranslateTransform(c.Left - Left, c.Top - Top)
e.Graphics.DrawImageUnscaled(bmp, Point.Empty)
e.Graphics.TranslateTransform(Left - c.Left, Top - c.Top)
bmp.Dispose()
End If
Next
End If
End Sub
代码将覆盖 PictureBox 的 OnPaintBackground 事件,从而绘制它自己的透明背景。
5) 构建您的项目。
6) 从工具箱中选择您的组件并将其添加到您的表单中。
希望这会有所帮助!
结果:
编辑:
除了您的评论,首先通过Build > Build <your project name> 菜单构建您的项目。
然后您可以在工具箱顶部的<your project name> Components 类别下找到您的自定义控件。