Reputation: 16502
Currently my mousedown on the form will give me the x,y cords in a label. This label though when I click on it, I do not receive the mousedown. But when I put the code into the mousedown for the label, it gives the the cords based on the origin of the label and not the entire form.
My goal is to be able to detect x,y anywhere in the form. Even if it is on a label, button.
Thanks in advance.
Upvotes: 6
Views: 16079
Reputation: 21
I realize this was a while ago, but I figured it might help somebody. I think the way to around this is recursive:
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...
}
}
}
Upvotes: 2
Reputation: 31
You can get the location like this this.PointToClient(Cursor.Position) on form for each control.
Upvotes: 3
Reputation: 2205
You can adjust by this.Location
.
or use this.PointToClient(Cursor.Position)
on form and each control.
Upvotes: 2
Reputation: 45127
Seems a bit of a hack but ...
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;
}
}
Upvotes: 6
Reputation: 15780
protected override void OnMouseMove(MouseEventArgs mouseEv)
{
txtBoxX.Text = mouseEv.X.ToString();
txtBoxY.Text = mouseEv.Y.ToString();
}
Upvotes: 3