65.9K
CodeProject 正在变化。 阅读更多。
Home

如何在 VB 2008 中创建透明控件

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.53/5 (8投票s)

2009 年 4 月 12 日

CPOL
viewsIcon

50937

downloadIcon

2

如何在 VB 2008 中创建透明控件

引言

本文档提供了在 VB 2008 中实现控件透明度所需的代码。

背景

VB 2008 中的透明度选项不如预期有用,因为 Transparency 设置会导致应用程序隐藏控件下方的所有图形,一直到窗体背景。

使用代码

以下提供的代码可以直接复制到您的项目中。它通过使用 Graphics 对象的“CopyFromScreen”方法,将给定控件后方的屏幕区域的快照复制到位图中。然后,该位图被分配为控件的 BackImage

Public Sub SetBackgroundTransparent(ByRef theCtl As Control)

    'This routine makes a control appear to be transparent
    'Transparency in VB2008 is implemented in a bit of an odd way. 
    'When the backcolor is set to Transparent, the control 
    'erases everything behind it except the form
    'so if you have a number of layered controls, 
    'you appear to see a "hole" in the display
    'This routine works by taking a snapshot of the area behind 
    'the control and copying this as a bitmap to the
    'backimage of the control.
    'The control isn't truly transparent, but it appears to be.

    'Incoming variable:  the control to be made transparent

    Dim intSourceX As Integer
    Dim intSourceY As Integer
    Dim intBorderWidth As Integer
    Dim intTitleHeight As Integer
    Dim bmp As Bitmap
    Dim MyGraphics As Graphics

    'get the X and Y corodinates of the control, 
    'allowing for the border and titlebar dimensions
    intBorderWidth = (Me.Width - Me.ClientRectangle.Width) / 2
    intTitleHeight = ((Me.Height - (2 * intBorderWidth)) - _
                       Me.ClientRectangle.Height)

    intSourceX = Me.Left + intBorderWidth + theCtl.Left

    intSourceY = Me.Top + intTitleHeight + intBorderWidth + theCtl.Top

    'Hide the control otherwise we end up getting a snapshot of the control
    theCtl.Visible = False

    'Give the UI some time to hide the control
    Application.DoEvents()

    'Take a snapshot of the screen in the region behind the control 
    bmp = New Bitmap(theCtl.Width, theCtl.Height)
    MyGraphics = Graphics.FromImage(bmp)
    MyGraphics.CopyFromScreen(intSourceX, intSourceY, 0, 0, bmp.Size)
    MyGraphics.Dispose()

    'use this clip as a the back image of the label
    theCtl.BackgroundImageLayout = ImageLayout.None
    theCtl.BackgroundImage = bmp
    'show the control with its new backimage
    theCtl.Visible = True
    'Give the UI some time to show the control
    Application.DoEvents()

End Sub
© . All rights reserved.