Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get X, Y positions of mouse relative to form even when clicking on another control?

Tags:

c#

winforms

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.

like image 931
RoR Avatar asked Oct 04 '10 02:10

RoR


3 Answers

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;
    }
}
like image 80
JP Alioto Avatar answered Sep 21 '22 13:09

JP Alioto


protected override void OnMouseMove(MouseEventArgs mouseEv) 
{ 
    txtBoxX.Text = mouseEv.X.ToString(); 
    txtBoxY.Text = mouseEv.Y.ToString(); 
} 
like image 23
Ruel Avatar answered Sep 20 '22 13:09

Ruel


You can get the location like this this.PointToClient(Cursor.Position) on form for each control.

like image 38
user466951 Avatar answered Sep 18 '22 13:09

user466951