14

I have a Picture Box with a picture loaded and I want to read the location (as in x,y inside the Picture Box) when I click the image; is this possible ? Even more, can i read these coordinates (Points) when i mouse over ?

I know i have to use the events given (Mouse Click and Mouse Over) but don't know how to read the coordinates where the mouse pointer happens to be.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Razvan
  • 187
  • 1
  • 1
  • 8

4 Answers4

34

Though other answers are correct let me add my point to it. You've pointed that you need to hook up MouseClick or MouseOver events for this purpose. Actually that is no need to hook those events to get Coordinates, you can get the Coordinates in just Click event itself.

private void pictureBox1_Click(object sender, EventArgs e)
{
    MouseEventArgs me = (MouseEventArgs)e;
    Point coordinates = me.Location;
}

The above code works since Click event's e argument wraps MouseEventArgs you can just cast it and make use of it.

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
  • 1
    This is the answer if OP wants to (I guess obviously) get the click point coordinates relative to the picturebox. – bonCodigo Jul 01 '14 at 02:45
  • This is correct as long as there are no transformations on the image as it is rendered in the `PictureBox`. If the rendered version is stretched, scaled, or panned, then the `MouseEventArgs.Location` property will need identical transformations applied to get the click in image coordinates. – kdbanman Aug 20 '15 at 15:28
  • @kdbanman what does transformations has to do with getting the clicked location of picture box? Op needs mouse coordinates with respect to picture box not image inside it. – Sriram Sakthivel Aug 20 '15 at 15:33
5

You can get the X and Y coordinates as follows,

 this.Cursor = new Cursor(Cursor.Current.Handle);

  int xCoordinate = Cursor.Position.X;
  int yCoordinate = Cursor.Position.Y;

If you want to get the coordinate within the picture box, use the following code,

private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
    int xCoordinate = e.X;
    int yCoordinate = e.Y;
}
Kurubaran
  • 8,696
  • 5
  • 43
  • 65
5

i'll just sum up the answers:

in MouseClick, MouseUp and a lot of other events you have the MouseEventArgs which contains Location of the mouse.

in MouseHover however you don't have MouseEventArgs and therefor, if you need the cursor's location, use Coder example:

  private void Form1_MouseHover(object sender, EventArgs e)
  {
     this.Cursor = new Cursor(Cursor.Current.Handle);

     int xCoordinate = Cursor.Position.X;
     int yCoordinate = Cursor.Position.Y;
  }
No Idea For Name
  • 11,411
  • 10
  • 42
  • 70
1

What about hooking up the MouseUp event and then getting the location from the MouseEventArgs?

Like this:

private void pictureBox_MouseUp(object sender, MouseEventArgs e)
{
    Point mousePointerLocation = e.Location;
}
jmelhus
  • 1,130
  • 2
  • 12
  • 28