Cursor Position relative to Application

2019-01-15 12:14发布

问题:

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?

回答1:

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);


回答2:

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.


回答3:

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());
  }