相对于应用程序的光标位置

时间:2013-10-03 16:57:09

标签: c# winforms cursor

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

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

但这与屏幕有关。我如何得到相对于我的表格的坐标?

3 个答案:

答案 0 :(得分:26)

使用Control.PointToClient method。假设this指向相关表单:

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

或者简单地说:

var relativePoint = this.PointToClient(Cursor.Position);

答案 1 :(得分:3)

我会像这样使用PointToClient

Point p = yourForm.PointToClient(Cursor.Position);
//if calling it in yourForm class, just replace yourForm with this or simply remove it.

答案 2 :(得分: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());
  }