Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent repeating code using events

Tags:

c#

I am a beginner programmer and I feel like I am repeating code unnecessarily. I want to make a picture puzzle game consisting of 16 pictureboxes. The problem is that I feel like I have to repeat code for each picturebox's events as in the below example:

       Point move;
    bool isDragging = false;
    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        isDragging = true;
        move = e.Location;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {

        if(isDragging == true)
        {
            pictureBox1.Left += e.X - move.X;
            pictureBox1.Top += e.Y - move.Y;
            pictureBox1.BringToFront();
        }

    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        isDragging = false;
    }
like image 419
behnam Avatar asked Dec 24 '22 07:12

behnam


2 Answers

Just create one method for each of your 3 events:

private void pictureBox_MouseDown(object sender, MouseEventArgs e)
{
    isDragging = true;
    move = e.Location;
}

private void pictureBox_MouseMove(object sender, MouseEventArgs e)
{

    if(isDragging == true)
    {
        // Luckily the sender parameter will tell us which PictureBox we are dealing with
        PictureBox pb = (PictureBox)sender;
        pb.Left += e.X - move.X;
        pb.Top += e.Y - move.Y;
        pb.BringToFront();
    }

}

private void pictureBox_MouseUp(object sender, MouseEventArgs e)
{
    isDragging = false;
}

Then go to each of your 16 picture boxes in the designer and set the MouseUp event handler to point to pictureBox_MouseUp and the MouseMove event handler to point to pictureBox_MouseMove and the MouseDown event handler to point to pictureBox_MouseMove. Do this for each of the 16 picture boxes.

like image 146
Icemanind Avatar answered Dec 29 '22 06:12

Icemanind


Try to trigger same events for all PictureBox Controls

private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    isDragging = true;
    move = e.Location;
}

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    PictureBox pictureBox = sender as PictureBox;
    if(isDragging == true)
    {
        pictureBox .Left += e.X - move.X;
        pictureBox .Top += e.Y - move.Y;
        pictureBox .BringToFront();
    }

}

private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
    isDragging = false;
}
like image 30
Jaydip Jadhav Avatar answered Dec 29 '22 06:12

Jaydip Jadhav