Mordacai1000
Mordacai1000

Reputation: 339

Cursor Position relative to Application

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?

Upvotes: 23

Views: 48738

Answers (3)

lc.
lc.

Reputation: 116458

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

Upvotes: 30

Rahul Tripathi
Rahul Tripathi

Reputation: 172408

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

Upvotes: 2

King King
King King

Reputation: 63317

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.

Upvotes: 3

Related Questions