C# Mouse position over pictureBox

28,185

Solution 1

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;

Solution 2

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.

Solution 3

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()

Solution 4

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);
Share:
28,185
NewProger
Author by

NewProger

I'm trying to learn several programming languages. Mostly C# and PHP, I'm no pro, so I may sometimes ask silly things, but please bear with me :) PS - also english is not my native language.

Updated on July 29, 2022

Comments

  • NewProger
    NewProger almost 2 years

    How can I know at what pixel of a pictureBox the mouse is placed (coordinates)?