4
votes

I am working on a windows form that is covered in panels representing a grid.

I'm trying to create an event handler that handles all mouse clicks regardless of which panel the click occurs on and then moves a PictureBox to the location of the panel.

I managed to find a topic that covered the event handler, but I am unable to get the location of the mouse click from the event handler. Below is the code I have so far (mostly pinched from another post):

private void Form1_Load(object sender, EventArgs e)
{
    foreach (Control c in this.Controls)
    {
        c.MouseClick += new MouseEventHandler(myEvent_handler_click);
    }
}

public void myEvent_handler_click(object sender, EventArgs e)
{
    Point point = new Point(e.X, e.Y);

    game.MoveToSquare(point);
}

The line of code Point point = new Point(e.X, e.Y); doesn't work because I can't refer to the X of e or the Y of e.

How can I get the location of the mouse at the time it is clicked?

Any help is appreciated. Feel free to ask me more questions if I wasn't clear enough!

1

1 Answers

1
votes

The delegate for the event handler is defined like so:

public delegate void MouseEventHandler(object sender, MouseEventArgs e);

MouseEventArgs inherits from EventArgs, that's why your code is working. If you change the definition of your EventHandler, you should be able to access the coordinates:

public void myEvent_handler_click(object sender, MouseEventArgs e)
{
    Point point = new Point(e.X, e.Y);
}

You can also simply access e.Location to get point:

Point point = e.Location;