21

我知道如何获取光标的位置:

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

但这是相对于屏幕而言的。我如何获得相对于我的表格的坐标?

4

3 回答 3

28

使用Control.PointToClient方法。假设this指向有问题的表格:

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

或者简单地说:

var relativePoint = this.PointToClient(Cursor.Position);
于 2013-10-03T17:02:45.043 回答
3

我会这样使用PointToClient

Point p = yourForm.PointToClient(Cursor.Position);
//if calling it in yourForm class, just replace yourForm with this or simply remove it.
于 2013-10-03T17:02:17.197 回答
2

如何使用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());
  }
于 2013-10-03T17:02:24.087 回答