Loeli
Loeli

Reputation: 75

VB: How can I make buttons over a picture box transparent?

in my program I have a picture box with a specific width x and height y. Then the user can enter an elementsize (e.g. 10) and then the programm will create buttons with the width and height of the elementsize over the picture box. The thing is that these buttons need to be transparent so only their border is visible. That means that through the buttons you can see the content of the picture box.

So this is my code for creating these buttons when I click on my start button:

Imports System.Math
Public Class Form1
Dim x As Double
Dim y As Double
Dim elsize As Integer
Dim numberofbuttons As Integer


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    x = 400
    y = 200
    elsize = 20

    numberofbuttons = Round(x / elsize) * Round(y / elsize)
    Dim i As Integer
    Dim j As Integer
    For j = 1 To Round(y / elsize)
        For i = 1 To Round(x / elsize)
            Dim Btn As New Button
            Btn.Width = elsize
            Btn.Height = elsize
            Btn.Location = New Point(elsize * (i - 1), elsize * (j - 1))
            Btn.BackColor = Color.Transparent
            PictureBox1.Controls.Add(Btn)

        Next
    Next

End Sub
End Class

I use

Btn.BringToFront()

to put these buttons in front of the picture box and I wanted to use

Btn.BackColor = Drawing.Color.Transparent

to make them transparent but this won't work. Has anybody any ideas how to do this? Also I wanted to put these buttons in the coordinate system of the picture box and not of the form1. I thought that this is possible through

Btn.Parent = PictureBox1

but the buttons always use the coordinate system of the form.

Thanks in advance for your help.

Upvotes: 1

Views: 3197

Answers (1)

jmcilhinney
jmcilhinney

Reputation: 54417

This:

Me.Controls.Add(Btn)

is setting the Parent of the Button to be the form. You don't Add to one parent and assign a different parent explicitly. Do one or the other. In short, get rid of that Add call and you should be good to go. Alternatively, get rid of the Parent assignmnent and Add to the Controls collection of the PictureBox instead. I'd suggest the latter.

Either way, DO NOT display the Button until you have configured it, i.e. set the Parent or call Controls.Add last.

EDIT: I tested this code and it worked as expected:

Dim btn As New Button

With btn
    .Size = mySize
    .Location = myLocation
    .BackColor = Color.Transparent
    .FlatStyle = FlatStyle.Flat

    PictureBox1.Controls.Add(btn)
End With

Upvotes: 3

Related Questions