简体   繁体   中英

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

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.

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;
    }
}
protected override void OnMouseMove(MouseEventArgs mouseEv) 
{ 
    txtBoxX.Text = mouseEv.X.ToString(); 
    txtBoxY.Text = mouseEv.Y.ToString(); 
} 

您可以在窗体上为每个控件获取像this.PointToClient(Cursor.Position)这样的位置。

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...
     }
}
}

You can adjust by this.Location .
or use this.PointToClient(Cursor.Position) on form and each control.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM