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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19164933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:17:12  来源:igfitidea点击:

Cursor Position relative to Application

c#winformscursor

提问by Mordacai1000

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?

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

采纳答案by lc.

Use the Control.PointToClientmethod. Assuming thispoints to the form in question:

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

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

Or simply:

或者干脆:

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

回答by King King

I would use PointToClientlike this:

我会这样使用PointToClient

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

回答by Rahul Tripathi

How about trying like this using the Control.PointToClient:-

试试这样使用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());
  }