在标签内未检测到PictureBox上的鼠标单击位置 [英] Mouse Click Location On A PictureBox Not Detected Within Label

查看:148
本文介绍了在标签内未检测到PictureBox上的鼠标单击位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个仅包含2个内容的表单,一个 PictureBox 和一个 Label .

I have a Form that contains only 2 things, a PictureBox and a Label.

我在图片框中添加了一个鼠标单击事件处理程序.

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!");
    }
}

我希望它可以工作,因为它看起来似乎很容易,但是导致显示MessageBox的单击位置(图像中的橙色框)在标签的右下角偏移.

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.

这是因为鼠标事件与PictureBox有关,而Label范围与Form有关吗?反之亦然?

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()
{
    InitializeComponent();
    this.label1.Visible = false;
    this.pictureBox1.MouseClick += picture_MouseClick;
}

(我尝试从e.X中减去标签的宽度,从e.Y中减去标签的高度,但这似乎不起作用.)

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

谢谢

Jan

推荐答案

e.Location是相对于图片框左上角的鼠标位置(一个点).
Bounds属性是相对于控件容器的.
(在这种情况下,容器就是表单,正如您和SLacks正确指出的那样)

The e.Location is the mouse position (a point) relative to the upper-left corner of the picturebox.
The 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;
if(label1.Bounds.Contains(p))
   .....

这篇关于在标签内未检测到PictureBox上的鼠标单击位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆