Search code examples
c#winformspictureboxmouseclick-event

Getting Form mouse coordinated on PictureBox on mouse click override - C#


I'm drawing a MyPictureBox which inherits from PictureBox, and i override it's OnMouseClick
I set the arguments to be :(MouseEventArgs e) so i get the mouse coordinated when clicked,
The problem is the coordinates are the MyPictureBox relative coordinates while i need the coordinated from the Form.

How can it be done ?

Thanks


Solution

  • First map the passed mouse coordinate to the screen. Then map it back to the client coordinates of the form. So the typical code would look like this, spelled out for clarity:

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e) {
            var pbox = (PictureBox)sender;
            var form = this;
            var screenPos = pbox.PointToScreen(e.Location);
            var formPos = form.PointToClient(screenPos);
            // etc..
        }
    

    Or the short version:

        private void pictureBox1_MouseDown(object sender, MouseEventArgs e) {
            var formPos = this.PointToClient(pictureBox1.PointToScreen(e.Location));
            // etc..
        }