Search code examples
c#mousehovereventargs

Adding parameters to method in mousehoover


I am having trouble making a mouse hoover method. The code is firstly a for-loop in which I create pictureboxes, and in the same for loop I would like to use the x and y worths in the loop.

This is the code where I create pictureboxes:

for (int x = 0; x < 9; x++){
    for (int y = 0; y < 9; y++){
        pb[x, y] = new PictureBox();
        pb[x, y].Location = new Point(x * 50 + 100, y * 50 + 100);
        pb[x, y].Width = 50;
        pb[x, y].Height = 50;
        pb[x, y].Visible = true;
        pb[x, y].BorderStyle = BorderStyle.FixedSingle;
        pb[x, y].BringToFront();
        this.Controls.Add(pb[x, y]);
        EventArgs e = new EventArgs();
        object sender;
        pb[x, y].MouseHover += new EventHandler(actionmousehoover(x, y, object sender));
    }    
}

The method called actionmousehoover is this one:

private void actionmousehoover(int x, int y,object sender, System.EventArgs e){
    resethoovercolors();
    //Om vertikal
    if(vertorhoriz = false){
        if(y+1 < 10 || y-1 < 1){
            pb[x, y].BackColor = Color.Red;
            pb[x, y + 1].BackColor = Color.Red;
            pb[x, y - 1].BackColor = Color.Red;

        }
    }
    if(vertorhoriz = true){
        if(x+1 < 10 || y-1 < 1){
            pb[x, y].BackColor = Color.Red;
            pb[x + 1, y].BackColor = Color.Red;
            pb[x - 1, y].BackColor = Color.Red;
        }
    }
}

The part with this:

pb[x, y].MouseHover += new EventHandler(actionmousehoover(x, y));

is working fine aswell as the actionmousehoover method do not have x and y as inparameter.


Solution

  • You can achieve this my creating your own picture box control that inherits from PictureBox and then add your own properties that you need.

    public class MyPictureBox : PictureBox
    {
        public int X { get; set; }
        public int Y { get; set; }
    }
    
    
    MyPictureBox box = new MyPictureBox()
    {
        Name = "pcBox1",
        X = 1,
         Y = 2
    };
    
    box.MouseHover += pictureBox1_MouseHover;
    

    Then in the event handler, cast the sender to your control and access the properties.

    private void pictureBox1_MouseHover(object sender, EventArgs e)
    {
         var x = ((MyPictureBox)sender).X;
         var y = ((MyPictureBox)sender).Y;
    }
    

    Hope that helps