Sudantha
Sudantha

Reputation: 16224

C# detect where user clicked on a image/Bitmap

Is it possible to detected where user clicked on a loaded image or a bitmap on a C# form ? . just need it to be independent to image not screen locations !

Upvotes: 0

Views: 1649

Answers (1)

Ed Swangren
Ed Swangren

Reputation: 124800

Well, you don't tell us how you are displaying the image, so I am forced to guess. I am assuming a picturebox displaying the image at it's native resolution. So, in that case:

class MyForm : Form
{
    public MyForm()
    {
        picturebox1.MouseDown += picturebox1_MouseDown;       
    }

    private void picturebox1_MouseDown( object sender, MouseEventArgs e )
    {
        if( (e.Button & MouseButtons.Left) == MouseButtons.Left )
        {
            var imagePos = e.Location; // that's it
        }
    }
}

If your image is scaled you will need to do the math. Get the Width and Height of the control and figure out the ratio between them and the dimensions of your image. Multiply the click position by that ratio.

Upvotes: 3

Related Questions