目前,当我在表单上按下鼠标时,会在标签中显示x、y坐标。但是,当我在该标签上单击时,却无法接收到鼠标按下事件。但是,当我将代码放入标签的mousedown中时,它会根据标签的原点而不是整个表单给出坐标。
我的目标是能够在表单的任何位置检测到x、y坐标,即使它在标签或按钮上也可以。
提前感谢。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
foreach (Control c in this.Controls)
{
c.MouseDown += ShowMouseDown;
}
this.MouseDown += (s, e) => { this.label1.Text = e.X + " " + e.Y; };
}
private void ShowMouseDown(object sender, MouseEventArgs e)
{
var x = e.X + ((Control)sender).Left;
var y = e.Y + ((Control)sender).Top;
this.label1.Text = x + " " + y;
}
}
protected override void OnMouseMove(MouseEventArgs mouseEv)
{
txtBoxX.Text = mouseEv.X.ToString();
txtBoxY.Text = mouseEv.Y.ToString();
}
我知道这是一段时间以前的事情,但我认为这可能会对某些人有所帮助。我认为解决这个问题的方法是递归:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
label1.MouseDown += MyMouseDown;
}
void MyMouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)//If it's left button that's the trigger
{
Control c = (Control)sender;
if (c.Parent == null) return;//Has no more children, wrong condition?
if(c.Parent != this)//We've reached top level
{
MyMouseDown(c.Parent, new MouseEventArgs(e.Button,
e.Clicks,
c.Parent.Location.X + e.X,
c.Parent.Location.Y + e.Y,
e.Delta));
return;
}
//Do what shall be done here...
}
}
}
this.Location
进行调整。this.PointToClient(Cursor.Position)
。