Reputation: 3085
How can I know at what pixel of a pictureBox
the mouse is placed (coordinates)?
Upvotes: 5
Views: 29094
Reputation: 1206
You can use the Curser.Position
in combination with the PointToClient
method of the PictureBox
, as explained in this answer.
Upvotes: 0
Reputation: 8116
If you determine the color inside a MouseEvent, you can just use the coordinates provided from MouseEventArgs
// Declare a Bitmap
Bitmap mybitmap;
// Load Picturebox image to bitmap
mybitmap = new Bitmap(pictureBox1.Image);
// In the mouse move event
var pixelcolor = mybitmap.GetPixel(e.X, e.Y);
// Displays R / G / B Color
pixelcolor.ToString()
Upvotes: 2
Reputation: 57593
Catch mouse move event:
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
Text = String.Format("X: {0}; Y: {1}", e.X, e.Y);
}
You have X and Y position there.
If your image has been zoomed and/or panned, rememeber you have to apply transformations on those coords.
To be clear: if your image has been placed on (x0,y0)
and been zoomed with zf
(remember that zf<1 means reduced), pixel coords will be
px = (e.X - x0) / zoom;
py = (e.Y - y0) / zoom;
Upvotes: 8
Reputation: 52205
I think that the question is a little bit vague since you did not tell us what exactly are you planning to do nor what you have effectively tried.
The Control.PointToClient method seems to do what you need:
Computes the location of the specified screen point into client coordinates.
You can then use the Bitmap.GetPixel and use the X-Y coordinates to get the pixel at the given mouse co-ordinates:
Gets the color of the specified pixel in this Bitmap
All of this can be triggered by a Mouse_Over event, Mouse_Click, etc.
Upvotes: 4
Reputation: 16043
There is a static method on the Mouse class that allows you to get the position of the mouse pointer relative to another element . Look at Mouse.GetPosition(UIElement).
Here's how you use it.
Point point = Mouse.GetPosition(pictureBox);
Debug.WriteLine("X: " + point.X +"\n Y: "+ point.Y);
Upvotes: 1