C# Tutorial – How to add picture boxes in random positions and remove with click event

Hi Welcome to another Windows form application and C# programming tutorial. In this tutorial we will explore how to make a windows form application that will spawn a picture box on the form every second and then it will be linked to a click event which will trigger when the user clicks on it. Once the picture box is clicked it will be removed from the form. This is a useful method for games such as when you want to drop an item or spawn enemies and remove them from the game when they no longer needed. This app will use the click events to control the other picture boxes. In the next one we will show how to do one where you can move your own player picture box and collect them on the form.

Lesson Objectives:

  • Create a simple application in Visual Studio Using Windows Form Application framework
  • Randomly assign X and Y values to the picture boxes
  • Dynamically spawn picture boxes with its own properties in the windows form application
  • Dynamically assign CLICK event to the picture box
  • CLICK to remove the picture box
  • Add the picture boxes to LISTS and keep track of how many picture boxes are on the form at a time

Full Video Tutorial

 

Full Source Code –

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Windows_Form_Spawn_and_Click_Picture_Box_MOO_ICT
{
    public partial class Form1 : Form
    {

        Random rand = new Random();
        List<PictureBox> items = new List<PictureBox>();
        public Form1()
        {
            InitializeComponent();
        }
        private void MakePictureBox()
        {

            PictureBox newPic = new PictureBox();
            newPic.Height = 50;
            newPic.Width = 50;
            newPic.BackColor = Color.Maroon;

            int x = rand.Next(10, this.ClientSize.Width - newPic.Width);
            int y = rand.Next(10, this.ClientSize.Height - newPic.Height);
            newPic.Location = new Point(x, y);

            newPic.Click += NewPic_Click;

            items.Add(newPic);
            this.Controls.Add(newPic);
        }

        private void NewPic_Click(object sender, EventArgs e)
        {
            PictureBox temPic = sender as PictureBox;

            items.Remove(temPic);

            this.Controls.Remove(temPic);

            lblItemCount.Text = "Items: " + items.Count();
        }

        private void TimerEvent(object sender, EventArgs e)
        {
            MakePictureBox();

            lblItemCount.Text = "Items: " + items.Count();
        }
    }
}

 




Comments are closed.