Search code examples
c#arraysbuttonmultidimensional-arraymousehover

Getting location of button in grid from Mousehover (C# VS)


in school I'm currently working on a game of battleships for AP Comp Sci and I have been trying to get it so that during the ship placing stage a picturebox (a ship) changes location to that of whichever button the mouse happens to be hovering over. This is supposed to act like a ghost icon for where you would be placing the ship. The buttons are in an array as they are made in a grid using a 2D forloop.

I couldn't figure out how to make MouseHover work with getting a buttons location from an array of buttons. This is mostly because I don't know how to give the x y values for the buttons location in the array to the MouseHover method.

I tried using a timer that checked each button in the array for whether it had focus and it changed the location of the picturebox to that button successfully:

private void MouseXYCheckTimer_Tick_1(object sender, EventArgs e)
    {
        for (int x = 0; x < 15; x++)
        {
            for (int y = 0; y < 15; y++)
            {
                if (b[x, y].Focused)
                {
                    ShipImage1.Location = b[x, y].Location;
                }
            }

        }
    }

however this required clicking the button to give it focus (thus placing the ship), defeating the purpose.

I've looked quite extensively at different posts here on MouseHover and I still cant get it to work for my problem, help would be greatly appreciated. Thanks!


Solution

  • There are built in events for handling MouseEnter

    // Wire up the MouseEnter event when creating your buttons
    button.MouseEnter += button_MouseEnter;
    
    // Method that gets called
    private void button_MouseEnter(object sender, EventArgs e)
    {
        var button = sender as Button;
        ShipImage1.Location = button.Location;
    }