Search code examples
c#.netwinformsbuttonpicturebox

How do I use a PictureBox as a Button


I'd like to create a roulette game, and I've made a PictureBox with an image of a roulette table.

I've tried to set Visibility = False in the property and in code:

pictureBox1.Visible = !pictureBox1.Visible;

But when I click on the hidden PictureBox, nothing happens.

Do you have any idea how to make it work?

I want to make it visible from being invisible, by clicking on it.


Solution

  • Once you make the visibility of an Item false, it can no longer be clicked. You can handle the click event on the form or container level, check that the mouse coordinates are contained in the bounds of the PictureBox and use that to make it visible again.

    i.e.

    //Common eventhandler assigned to all of your PictureBox.Click Events
    private void pictureBox_Click(object sender, EventArgs e)
    {
        ((PictureBox)sender).Visible = false;
    }
    
    private void Form1_Click(object sender, EventArgs e)
    {
        foreach (var item in this.Controls) // or whatever your container control is
        {
            if(item is PictureBox)
            {
                PictureBox pb = (PictureBox)item;
                if (pb.Bounds.Contains(PointToClient( MousePosition)))
                {
                    pb.Visible = true;
                }
            }
        }
    }