Ubicación del clic del mouse en un PictureBox no detectado dentro de la etiqueta

I have a Form that contains only 2 things, a Picturebox y Disquera.

I added a mouse click event handler to the picture box.

this.pictureBox1.MouseClick += picture_MouseClick;

Inside the handler I need to check if the location of the mouse click is within the bounds of the label. To do this, I am using the mouse event location and checking to see whether that location is within the bounds of the label.

private void picture_MouseClick(object sender, MouseEventArgs e)
    if (label1.Bounds.Contains(e.Location))
        MessageBox.Show("FOUND YOU!");

I expected this to work as it seems easy enough however the click location (the orange box in the image) that leads to the MessageBox being shown is offset down and to the right of the label.

Form With Label

Is this because the mouse event is relative to the PictureBox and the Label bounds are relative to the Form? Or vice versa?

By the way, the label you see in the image is hidden at runtime. I am just using the label as a "hack" way of knowing if the user clicked in a certain spot.

public Form1()
    this.label1.Visible = false;
    this.pictureBox1.MouseClick += picture_MouseClick;

(I tried subtracting the width of the label from e.X and the height of the label from e.Y but that didn't seem to work.)



preguntado el 26 de agosto de 12 a las 23:08

If you click on the label, the PictureBox's Click event won't fire. -

Ah but here is the trick! I actually hide the label at runtime. I am just using the label's bounds to know where the mouse was clicked. What I am really after here is something like a HTML image map and I am using a hidden label's location to check the location of the mouse click. -

1 Respuestas

El sistema e.Location is the mouse position (a point) relative to the upper-left corner of the picturebox.
El sistema Bounds property is relative to the container of the control.
(And in this case, the container is the form, as you and SLacks have rightly pointed out)

To check the correct position I will try with this code (now tested)

Point p = e.Location;
p.X += pictureBox1.Left;
p.Y += pictureBox1.Top;

Respondido 27 ago 12, 00:08

Well, I am using Visual Studio and I just arrastrado a PictureBox over to my form then arrastrado a label over top of the PictureBox. I doubt a PictureBox can contain a label so it's parent is probably the Form. - Jan Tacci

@Steve: No; PictureBox no es un contenedor. - SLaks

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.