22

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?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Mordacai1000
  • 329
  • 1
  • 3
  • 14

3 Answers3

29

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);
lc.
  • 113,939
  • 20
  • 158
  • 187
  • I used : var relativePoint = this.PointToClient(Cursor.Position); but it stil returns the screen coordinates – Mordacai1000 Oct 03 '13 at 17:11
  • Just tried it and it works for me: `var cpos = Cursor.Position; MessageBox.Show(String.Format("{0}\n{1}", cpos, this.PointToClient(cpos)));` gives two different points – lc. Oct 03 '13 at 17:16
  • 1
    @Mordacai1000 **it's hard to believe** what you said :)) Unless your form has no border and it's **maximized** to full screen. – King King Oct 03 '13 at 17:16
  • i see now, but this first point is relative to the screen(as it should be) but the second set of coordinates is -227 and -75, where it should be 0:0 – Mordacai1000 Oct 03 '13 at 18:08
3

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.
King King
  • 61,710
  • 16
  • 105
  • 130
2

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());
  }
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331