WPF C# Tutorial – Add and Remove Objects with Mouse Click in Visual Studio

This is an exciting tutorial; we will show you how to add rectangles to the mouse click location and when you click on the rectangles it will remove it from the app. This technique will be very useful for games development as we can dynamically add or remove objects from the screen as needed. We are using Microsoft visual studio 2017 to create this app you can follow along with any version that support WPF form app.

Lesson objective –

  • Create an app that adds and removes rectangles from the scene
  • Create mouse click events to work with canvas element in WPF
  • Capture mouse click location and add rectangles to that location
  • Capture mouse clicks on rectangles and remove the CLICKED rectangle
  • Add random colours to the rectangles to make them identifiable

Watch the video tutorial

 

Written Tutorials and Source Code Below –

Open Visual Studio and Start a new project

Name it Add and Remove Items Dynamically and click OK. Make sure you save this project file in a location where you can find it again.

This is the default view of the project so far. We will make some changes to the bottom part of the code here.

Add the highlighted part into the title of the app, this will trigger the focus manager and keep the main canvas in focus while the app is running.

We need to delete this Grid and add canvas here

This canvas we added has its own properties inside of it. First we gave it a name so we can interact with it from the C# script, we also set the focusable to true. This canvas has a mouse left button down event called addRemoveItems and it has a background colour of white.

The event add remove items will be used to check where we clicked on the canvas and were to add the items to. For now this is all we need for this canvas. Now we can go and start adding c# codes for this project.

Right click on the addRemoveItems keyword and click on goto definition

This will take us to the C# script page and add the definition automatically. You can type it manually but this way is faster.

This is the C# script for this app so far, we will need to add a couple of variables here and then we can start with the event.

Add the two following lines above the main window function. These two lines represent two variables we will need for this app. The first Brush Custombrush is a Brush variable that will let us create new colours for the boxes. We want to make each box different than the last so we need to make it a random colour so to be able generate random colours we need the second line. Random r = new Random() will help create random numbers between two values.

Lets program the add remove items event now and see what it does.

Here is the logic behind the event:

First we check if we click on a existing rectangle

IF so

Identify this rectangle

Remove the identified rectangle from the screen

IF NOT (ELSE)

Create a new rectangle (apply size, random colour, border etc)

Set the position of the rectangle to the click location (X and Y)

Add the rectangle to the screen

That’s it. Seems pretty simple lets see how it looks in the code. Below is the add more items event code

private void addRemoveItems(object sender, MouseButtonEventArgs e)
        {
            // this is the event that will check if we clicked on a rectangle or if we clicked on the canvas
            // if we clicked on a rectangle then it will do the following

            if (e.OriginalSource is Rectangle)
            {
                // if the click source is a rectangle then we will create a new rectangle
                // and link it to the rectangle that sent the click event
                Rectangle activeRec = (Rectangle)e.OriginalSource; // create the link between the sender rectangle

                MyCanvas.Children.Remove(activeRec); // find the rectangle and remove it from the canvas
            }

            // if we clicked on the canvas then we do the following
            else
            {
                // generate a random colour and save it inside the custom brush variable
                Custombrush = new SolidColorBrush(Color.FromRgb((byte)r.Next(1, 255),
                (byte)r.Next(1, 255), (byte)r.Next(1, 233)));

                // create a re rectangle and give it the following properties
                // height and width 50 pixels
                // border thickness 3 pixels, fill colour set to the custom brush created above
                // border colour set to black
                Rectangle newRec = new Rectangle
                {
                    Width = 50,
                    Height = 50,
                    StrokeThickness = 3,
                    Fill = Custombrush,
                    Stroke = Brushes.Black
                };

                // once the rectangle is set we need to give a X and Y position for the new object
                // we will calculate the mouse click location and add it there
                Canvas.SetLeft(newRec, Mouse.GetPosition(MyCanvas).X); // set the left position of rectangle to mouse X
                Canvas.SetTop(newRec, Mouse.GetPosition(MyCanvas).Y); // set the top position of rectangle to mouse Y

                MyCanvas.Children.Add(newRec); // add the new rectangle to the canvas
            }
        }

Lets break down the code and see what it does under the hood. There is 1 main if statement in this mouse event. However as you can see there is a lot going on here so we will take some time break down this code and explain what is happening here.

This is the first part of the event

if (e.OriginalSource is Rectangle)

{

// if the click source is a rectangle then we will create a new rectangle

// and link it to the rectangle that sent the click event

Rectangle activeRec = (Rectangle)e.OriginalSource; // create the link between the sender rectangle

MyCanvas.Children.Remove(activeRec); // find the rectangle and remove it from the canvas

}

In this section we are looking IF we clicked on a existing rectangle, if so we will link it with a local rectangle to help us identify the event sender and then we remove from the Canvas.

If the conditions above are not met for example if we did not click on an existing rectangle that means we want to add a new rectangle to the scene. This is when the ELSE part of the if statement comes in.

// if we clicked on the canvas then we do the following

else

{

// generate a random colour and save it inside the custom brush variable

Custombrush = new SolidColorBrush(Color.FromRgb((byte)r.Next(1, 255),

(byte)r.Next(1, 255), (byte)r.Next(1, 233)));

// create a re rectangle and give it the following properties

// height and width 50 pixels

// border thickness 3 pixels, fill colour set to the custom brush created above

// border colour set to black

Rectangle newRec = new Rectangle

{

Width = 50,

Height = 50,

StrokeThickness = 3,

Fill = Custombrush,

Stroke = Brushes.Black

};

// once the rectangle is set we need to give a X and Y position for the new object

// we will calculate the mouse click location and add it there

Canvas.SetLeft(newRec, Mouse.GetPosition(MyCanvas).X); // set the left position of rectangle to mouse X

Canvas.SetTop(newRec, Mouse.GetPosition(MyCanvas).Y); // set the top position of rectangle to mouse Y

MyCanvas.Children.Add(newRec); // add the new rectangle to the canvas

}

In this ELSE part first we are generating a random colour in the custom brush. Lets break it down and see what’s happening here

Inside the custom brush we are creating a new solid colour brush instance. This solid colour brush is a class and it takes 3 arguments for example we can say SolidColorBrush(Color.FromRGB(0,0,0,)); this will give us a black colour so each the numbers will be converted to bytes and then that will represent the values from Red Green and Blue part of the colours. Because we want to create random colours for each rectangle we are using Random R variable created earlier to generate a random number between 1 and 255 then converting them to bytes so they can be used as a colour input. FromRGB means from Red Green and Blue colours so we generate random numbers inside that.

Rectangle newRec = new Rectangle

{

Width = 50,

Height = 50,

StrokeThickness = 3,

Fill = Custombrush,

Stroke = Brushes.Black

};

Above we are making the new rectangle and we are giving the property values of the rectangle directly inside of it. So we create a new rectangle called newRec and this will be an instance of the rectangle class. This new rectangle will have 50 pixels height and width, 3-pixel border, custom fill colour and black border colour.

Canvas.SetLeft(newRec, Mouse.GetPosition(MyCanvas).X); // set the left position of rectangle to mouse X

Canvas.SetTop(newRec, Mouse.GetPosition(MyCanvas).Y); // set the top position of rectangle to mouse Y

These two lines above position the new rectangle to the mouse click location. We capture the mouse click X and Y value and assign it to the new rectangles left and top location.

MyCanvas.Children.Add(newRec); // add the new rectangle to the canvas

This line will add the new rectangle to the screen.

Let’s see it in action.

As you can see, we can add the rectangles and its showing different colours, when you click on the rectangles it removes it from the screen. If you have followed the tutorial so far then well done. If you are having difficulties then check the code again and make sure you have spelled them correctly.

Full Source code – 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Add_and_Remove_Items_Dynamically
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        Brush Custombrush; // new instace of the Brush class to create random colours for the boxes
        Random r = new Random(); // new random class to generate random numbers for the colours

        public MainWindow()
        {
            InitializeComponent();
        }

        private void addRemoveItems(object sender, MouseButtonEventArgs e)
        {
            // this is the event that will check if we clicked on a rectangle or if we clicked on the canvas
            // if we clicked on a rectangle then it will do the following

            if (e.OriginalSource is Rectangle)
            {
                // if the click source is a rectangle then we will create a new rectangle
                // and link it to the rectangle that sent the click event
                Rectangle activeRec = (Rectangle)e.OriginalSource; // create the link between the sender rectangle

                MyCanvas.Children.Remove(activeRec); // find the rectangle and remove it from the canvas
            }

            // if we clicked on the canvas then we do the following
            else
            {
                // generate a random colour and save it inside the custom brush variable
                Custombrush = new SolidColorBrush(Color.FromRgb((byte)r.Next(1, 255),
                (byte)r.Next(1, 255), (byte)r.Next(1, 233)));

                // create a re rectangle and give it the following properties
                // height and width 50 pixels
                // border thickness 3 pixels, fill colour set to the custom brush created above
                // border colour set to black
                Rectangle newRec = new Rectangle
                {
                    Width = 50,
                    Height = 50,
                    StrokeThickness = 3,
                    Fill = Custombrush,
                    Stroke = Brushes.Black
                };

                // once the rectangle is set we need to give a X and Y position for the new object
                // we will calculate the mouse click location and add it there
                Canvas.SetLeft(newRec, Mouse.GetPosition(MyCanvas).X); // set the left position of rectangle to mouse X
                Canvas.SetTop(newRec, Mouse.GetPosition(MyCanvas).Y); // set the top position of rectangle to mouse Y

                MyCanvas.Children.Add(newRec); // add the new rectangle to the canvas
            }
        }
    }
}

 




Comments are closed.