What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleMake buttons display the picture that is under them
Keywordsbutton, command button, picture
Make a hidden PictureBox. The SetButtonBackground subroutine that follows gets the button's size. It uses GetSystemMetrics to see how thick a button's borders are. Then it uses PaintPicture to copy the image beneath the button into the hidden PictureBox, starting at the position of the button's surface (the button's upper left corner offset by the border thicknesses).

Next the routine draws any desired button text on the hidden PictureBox. Use this PictureBox's Font properties to determine the button's font. Finally the program assigns the PictureBox's image to the button's Picture property. Note that the button's Style property must be set to Graphical at design time and that its Caption property should be set to "".

' Make the button display the picture beneath it.
Private Sub SetButtonBackground(ByVal btn As CommandButton, _
    ByVal txt As String)
Dim wid As Single
Dim hgt As Single
Dim xoff As Single
Dim yoff As Single

    ' Get the button size.
    wid = btn.Width
    hgt = btn.Height

    ' Get the button's border thickness.
    xoff = GetSystemMetrics(SM_CXFIXEDFRAME)
    yoff = GetSystemMetrics(SM_CYFIXEDFRAME)

    ' Size the hidden PictureBox to fit the button.
    picHidden.Move 0, 0, wid, hgt

    ' Copy the picture under the button to the PictureBox.
    picHidden.PaintPicture Picture, 0, 0, wid, hgt, _
        btn.Left + xoff, btn.Top + yoff, wid, hgt

    ' Add text to the image.
    ' Code Added by DiamondGeo to Include Text on Buttons
    ' Thanks to DiamondGeo <diamondgeo@diamondgeo.org>.
    picHidden.CurrentX = _
        (wid - picHidden.TextWidth(txt)) / 2
    picHidden.CurrentY = _
        (hgt - picHidden.TextHeight(txt)) / 2
    picHidden.Print txt
    picHidden.Picture = picHidden.Image

    ' Set the button's picture.
    btn.Picture = picHidden.Picture
End Sub
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.