Windows Forms cloning buttons/forms keeps cloning many times

41 views Asked by At

I am making a C# project where you have a transparent button with the DVD logo on it while it moves diagonally and moves in opposite direction of the window when collide with the borders. This project also makes certain functions when collisions with border and corners happen, event that are the following:

IF THE BUTTON TOUCHES THE TOP RIGHT CORNER: Increases the size of the shape and changes its color IF THE BUTTON TOUCHES THE BOTTOM LEFT CORNER: Decreases the size of the shape and changes its color IF THE BUTTON TOUCHES THE TOP LEFT CORNER: Increase the size of the button and change the color of the button IF THE BUTTON TOUCHES THE BOTTOM RIGHT CORNER: Decrease the size of the button and change the color of the button

IF THE BUTTON TOUCHES THE RIGHT BORDER OF THE SHAPE: every time you touch this side, a second button will appear, with the same characteristics and movement as the initial button (clone button).

IF THE BUTTON TOUCHES THE LEFT EDGE OF THE SHAPE: every time you touch this side a shape will appear, with the same characteristics as the initial shape (clone shape) limited to 5 shapes.

IF THE BUTTON TOUCHES THE TOP EDGE OF THE SHAPE: Remove a shape from the extra shapes that were created, the original shape will never disappear

IF THE BUTTON TOUCHES THE BOTTOM EDGE OF THE SHAPE: Removes a button from the extra buttons that were created, the original button will never disappear

BY CLICKING THE BUTTON: close the program WHEN YOU CLICK ON THE FORM: restarts the program and everything disappears.

I achieved these last two conditions and the corner ones, but when i start having problems is with the ones of colliding with borders. My code is the following:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.LinkLabel;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;

namespace Practica4_Bordes
{
    public partial class Form1 : Form
    {
        private readonly Button button1;
        private readonly Timer timer1;
        private int dx = 1;
        private int dy = 1;
        private List<Button> extraButtons = new List<Button>(); // Lista de botones clon
        private List<Form> extraForms = new List<Form>(); // Lista de formas clon
        public bool clonated = false;

        public Form1()
        {
            Size = new Size(400, 400);
            BackColor = Color.Black;
            button1 = new Button
            {
                BackColor = Color.Black,
                FlatStyle = FlatStyle.Flat,
                Size = new Size(100, 100),
                Location = new Point(0, 0),
                BackgroundImage = Image.FromFile(Path.Combine(Application.StartupPath, "dvd-512.png")),
                BackgroundImageLayout = ImageLayout.Stretch
            };

            timer1 = new Timer
            {
                Interval = 10
            };
            timer1.Tick += Timer1_Tick;

            this.Controls.Add(button1);
            timer1.Start();

            // Controladores de eventos para eventos Click del botón y de la forma
            this.Click += Form1_Click;
            button1.Click += Button1_Click;
        }

        private void Timer1_Tick(object sender, EventArgs e)
        {
            if (button1.Location.X + button1.Width > this.ClientSize.Width || button1.Location.X < 0)
            {
                dx = -dx;
            }
            if (button1.Location.Y + button1.Height > this.ClientSize.Height || button1.Location.Y < 0)
            {
                dy = -dy;
            }
            button1.Location = new Point(button1.Location.X + dx, button1.Location.Y + dy);

            //SI EL BOTON TOCA LA ESQUINA SUPERIOR DERECHA: Aumenta el tamaño de la forma y cambia su color
            if (button1.Location.X + button1.Width >= this.ClientSize.Width && button1.Location.Y <= 0)
            {
                // Aumenta el tamaño de la forma
                this.Size = new Size(this.Width + 10, this.Height + 10);

                // Cambia el color de la forma
                this.BackColor = Color.FromArgb(new Random().Next(256), new Random().Next(256), new Random().Next(256));
            }

            //SI EL BOTON TOCA LA ESQUINA INFERIOR IZQUIERDA: Disminuye el tamaño de la forma y cambia su color            
            if (button1.Location.X == 0 && button1.Location.Y + button1.Height == this.ClientSize.Height)
            {
                // Disminuye el tamaño de la forma y cambia su color
                this.Size = new Size(this.Width - 10, this.Height - 10);

                // Cambia el color de la forma
                this.BackColor = Color.FromArgb(new Random().Next(256), new Random().Next(256), new Random().Next(256));
            }

            //SI EL BOTON TOCA LA ESQUINA SUPERIOR IZQUIERDA: Aumentar el tamaño del botón y cambiar el color del botón
            if (button1.Location.X == 0 && button1.Location.Y == 0)
            {
                // Aumenta el tamaño del botón y cambia su color
                button1.Size = new Size(button1.Width + 10, button1.Height + 10);

                // Cambia el color de la forma
                button1.BackColor = Color.FromArgb(new Random().Next(256), new Random().Next(256), new Random().Next(256));
            }

            //SI EL BOTON TOCA LA ESQUINA INFERIOR DERECHA:  Disminuye el tamaño del botón y cambiar el color del botón
            if (button1.Location.X + button1.Width == this.ClientSize.Width && button1.Location.Y + button1.Height == this.ClientSize.Height)
            {
                // Disminuye el tamaño del botón y cambia su color
                button1.Size = new Size(button1.Width - 10, button1.Height - 10);

                // Cambia el color de la forma
                button1.BackColor = Color.FromArgb(new Random().Next(256), new Random().Next(256), new Random().Next(256));
            }

            //SI EL BOTON TOCA EL BORDE DERECHO DE LA FORMA: cada vez que toque este lado aparecerá un segundo botón, con las mismas características que el botón inicial (botón clon).
            if (button1.Location.X + button1.Width >= this.ClientSize.Width && button1.Location.Y >= 0 && button1.Location.Y + button1.Height <= this.ClientSize.Height && clonated == false)
            {
                // Crear un nuevo botón clon
                Button cloneButton = new Button
                {
                    BackColor = button1.BackColor,
                    FlatStyle = button1.FlatStyle,
                    Size = button1.Size,
                    Location = new Point(button1.Location.X - button1.Width, button1.Location.Y),
                    BackgroundImage = button1.BackgroundImage,
                    BackgroundImageLayout = button1.BackgroundImageLayout
                };

                // Agregar el botón clon a la lista de botones clon
                extraButtons.Add(cloneButton);

                // Agregar el botón clon a los controles de la forma
                this.Controls.Add(cloneButton);

                clonated = true;
            }

            //SI EL BOTON TOCA EL BORDE IZQUIERDO DE LA FORMA: cada vez que toque este lado aparecerá una forma, con las mismas características que la forma inicial (forma clon) limitados a 5 formas clon.
            if (button1.Location.X <= 0 && button1.Location.Y >= 0 && button1.Location.Y + button1.Height <= this.ClientSize.Height && extraForms.Count < 5)
            {
                // Crear una nueva forma clon
                Form cloneForm = new Form
                {
                    BackColor = this.BackColor,
                    Size = this.Size,
                    Location = new Point(this.Location.X - this.Width, this.Location.Y)
                };

                // Agregar la forma clon a la lista de formas clon
                extraForms.Add(cloneForm);

                // Mostrar la forma clon
                cloneForm.Show();

                clonated = true;
            }

            //SI EL BOTON TOCA EL BORDE SUPERIOR DE LA FORMA: Quitar una forma de las formas extras que fueron creadas, la forma original no debe desaparecer
            if (button1.Location.X >= 0 && button1.Location.X + button1.Width <= this.ClientSize.Width && button1.Location.Y <= 0)
            {
                // Verificar si hay formas extras creadas
                if (extraForms.Count > 0)
                {
                // Obtener la última forma clon de la lista
                Form lastCloneForm = extraForms.Last();

                // Quitar la última forma clon de los controles de la forma
                this.Controls.Remove(lastCloneForm);

                // Quitar la última forma clon de la lista de formas clon
                extraForms.Remove(lastCloneForm);
                }
            }

            //SI EL BOTON TOCA EL BORDE INFERIOR DE LA FORMA: Quita un botón de los botones extras que fueron creados, el boton original no debe desaparecer.
            if (button1.Location.X >= 0 && button1.Location.X + button1.Width <= this.ClientSize.Width && button1.Location.Y + button1.Height == this.ClientSize.Height)
            {
                // Verificar si hay botones extras creados
                if (extraButtons.Count > 0)
                {
                // Obtener el último botón clon de la lista
                Button lastCloneButton = extraButtons.Last();

                // Quitar el último botón clon de los controles de la forma
                this.Controls.Remove(lastCloneButton);

                // Quitar el último botón clon de la lista de botones clon
                extraButtons.Remove(lastCloneButton);
                }
            }
        }

        //AL DAR CLICK EN EL BOTON: cerrar  el programa
        private void Button1_Click(object sender, EventArgs e) //botón inicial
        {
            // Cierra la aplicación
            Application.Exit();
        }
        private void CloneButton_Click(object sender, EventArgs e) //botón clon
        {
            // Cierra la aplicación
            Application.Exit();
        }

        //AL DAR CLICK EN LA FORMA: reinicia el programa desapareciendo todo
        private void Form1_Click(object sender, EventArgs e) //forma inicial
        {
            // Reinicia la aplicación            
            Application.Restart();
        }
        private void CloneForm_Click(object sender, EventArgs e) //forma clon
        {
            // Reinicia la aplicación
            Application.Restart();
        }
    }
}

My problem starts with the fact the cloned buttons don't have movement and keep static, and when i modify the "Location = new Point(button1.Location.X - button1.Width, button1.Location.Y)," line to create cloned buttons in random coordinates, they create repeatedly many buttons on the collision with right border while the collision only should create ONE button, and it doesn't delete any button when colliding to bottom border.

Added to this, i have the same problem with the forms that create up to 3 clones each collision with left border without erasing any of them, and inside the cloned forms there's nothing but a black background collor of the original form; no button, no movement, no cloning.

I already tried putting the conditionals of collision out of the Timer1_Tick but it only creates more errors that make impossible to compile.

I tried to search here for ways to implement what the excercise requires, i created variables of the coordinates, along with two lists that'll store the cloned buttons and forms, and finally the movement of the button1.

First i created a timer that moves in interval of 25, then inside the Timer1_Tick i created the conditionals of colliding with borders that only makes the button move backwards of the border that collided; for example, if collides with bottom border, dy will move backwards in the Y axis while X axis moves normally until colliding with right border and moving backwards X axis and repeating.

Then i created the conditionals of the corners that change colors and increases or reduces the size of the form depending of the corner.

After that i created the conditionals of the borders, while creating both new Buttons and new Forms cloning the same characteristics of the original ones, while adding a new Button to both list and controls of the form, and new Forms to list and showing up the forms

I was expecting it to do as the indications say, but the clonned buttons and forms doesn't erase when colliding, button clones repeatedly while using random values, three forms are created when colliding. Buttons don't have movement nor collision physics and forms are empty.

0

There are 0 answers