光标位置相对于应用程序

22

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

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

但是这是相对于屏幕的坐标。我如何获取相对于我的表单的坐标?

3个回答

29

使用 Control.PointToClient 方法。假设 this 指向要操作的窗体:

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

或者简单点说:

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

我使用了:var relativePoint = this.PointToClient(Cursor.Position); 但它仍然返回屏幕坐标。 - Mordacai1000
刚试了一下,对我有效:var cpos = Cursor.Position; MessageBox.Show(String.Format("{0}\n{1}", cpos, this.PointToClient(cpos)));会给出两个不同的点。 - lc.
1
@Mordacai1000 很难相信你所说的 :)) 除非你的表单没有边框并且最大化到全屏。 - King King
我现在明白了,但是第一个点是相对于屏幕的(应该是这样),但第二组坐标是-227和-75,应该是0:0。 - Mordacai1000

3
我会这样使用 PointToClient
Point p = yourForm.PointToClient(Cursor.Position);
//if calling it in yourForm class, just replace yourForm with this or simply remove it.

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接