Cursor Position relative to Application

2019-01-15 12:43发布

I know how to get the cursor's position :

 int X = Cursor.Position.X;
 int Y = Cursor.Position.Y;

But this is relative to the screen. How do i get the coordinates relative to my Form?

3条回答
一夜七次
2楼-- · 2019-01-15 12:52

How about trying like this using the Control.PointToClient:-

public Form()
    {
        InitializeComponent();

        panel = new System.Windows.Forms.Panel();
        panel.Location = new System.Drawing.Point(90, 150);
        panel.Size = new System.Drawing.Size(200, 100);
        panel.Click += new System.EventHandler(this.panel_Click);
        this.Controls.Add(this.panel);
    }

  private void panel_Click(object sender, EventArgs e)
  {
    Point point = panel.PointToClient(Cursor.Position);
    MessageBox.Show(point.ToString());
  }
查看更多
放我归山
3楼-- · 2019-01-15 13:02

Use the Control.PointToClient method. Assuming this points to the form in question:

var relativePoint = this.PointToClient(new Point(X, Y));

Or simply:

var relativePoint = this.PointToClient(Cursor.Position);
查看更多
劳资没心,怎么记你
4楼-- · 2019-01-15 13:16

I would use PointToClient like this:

Point p = yourForm.PointToClient(Cursor.Position);
//if calling it in yourForm class, just replace yourForm with this or simply remove it.
查看更多
登录 后发表回答