Search code examples
c#mouseovermouseleavemousehover

C# cloned MouseHover/MouseLeave applies to original control & not current


I have a form that I add controls in a panel

one of them is a PictureBox holds a MouseHover/MouseLeave event like this

void PropAction_pBoxMouseLeave(object sender, EventArgs e)
{
    PropAction_pBox.ImageLocation = @"PicButtons\PropertiesBtn2.png";
}
void PropAction_pBoxMouseHover(object sender, EventArgs e)
{
    PropAction_pBox.ImageLocation = @"PicButtons\PropertiesBtn2White.png";
}

In the add button I have this code

create a new button based on the newPropAction (original) and add it in a list *

" newPropAction_pBox represents the new PictureBox & PropAction_pBox represents the original PictureBox "*

        PictureBox newPropAction_pBox = new PictureBox();
        newPropAction_pBox.Image = PropAction_pBox.Image;
        newPropAction_pBox.Click += PropAction_pBoxClick;
        newPropAction_pBox.MouseHover += PropAction_pBoxMouseHover;
        newPropAction_pBox.MouseLeave += PropAction_pBoxMouseLeave;
        this.Controls.Add(newPropAction_pBox);// add to controls
        ActionPictures.Add(newPropAction_pBox); //Add to btn to list    

But the final effect is this (pictures below)

Mouse not on pictureBox yet : http://prnt.sc/axt8b9

Mouse on the new PictureBox : http://prnt.sc/axt9ul


Solution

  • Change the code as follows

    void PropAction_pBoxMouseLeave(object sender, EventArgs e)
    {
        var pictureBox = (PictureBox)sender;
        pictureBox.ImageLocation = @"PicButtons\PropertiesBtn2.png";
    }
    
    void PropAction_pBoxMouseHover(object sender, EventArgs e)
    {
        var pictureBox = (PictureBox)sender;
        pictureBox.ImageLocation = @"PicButtons\PropertiesBtn2White.png";
    }
    

    Object sender is source of the event. Parameter sender refers to the instance that raises the event.
    Thus the event handler receives information, what kind of object is the source of this event.