【问题标题】:Cursor Position relative to Application相对于应用程序的光标位置
【发布时间】:2013-10-10 11:46:06
【问题描述】:

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

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

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

【问题讨论】:

    标签: c# winforms mouse-cursor


    【解决方案1】:

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

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

    或者简单地说:

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

    【讨论】:

    • 我用过:var relativePoint = this.PointToClient(Cursor.Position);但它仍然返回屏幕坐标
    • 刚刚尝试过,它对我有用:var cpos = Cursor.Position; MessageBox.Show(String.Format("{0}\n{1}", cpos, this.PointToClient(cpos))); 给出了两个不同的点
    • @Mordacai1000 很难相信你说的话 :)) 除非你的表单没有边框并且它最大化到全屏。
    • 我现在看到了,但第一个点是相对于屏幕的(应该是),但第二组坐标是 -227 和 -75,应该是 0:0
    【解决方案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());
      }
    

    【讨论】:

      【解决方案3】:

      我会像这样使用PointToClient

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-15
        相关资源
        最近更新 更多