Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

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());
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top