Reputation: 319
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.
Upvotes: 15
Views: 49580
Reputation: 73442
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.
Upvotes: 35
Reputation: 11577
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;
}
Upvotes: 5
Reputation: 8902
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;
}
Upvotes: 5
Reputation: 1140
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;
}
Upvotes: 1