从其他事件获取数据

本文关键字:数据 获取 事件 其他 | 更新日期: 2023-09-27 18:02:02

我们可以得到鼠标在图片框上移动的X和Y点,如;

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
     double Xcoordinate = e.X;
     double Ycoordinate = e.Y;
     label1.Text = Xcoordinate.ToString();
     label2.Text = Ycoordinate.ToString();
}

我的问题我怎么能得到Xcoordinate和Ycoordinate从其他事件为ex;鼠标点击事件或我的新定义的函数?

实际上我想从FormLoad中获取XCoordinate和Ycoordinate参数。我该怎么做呢?

从其他事件获取数据

使用光标位置属性…

 private void MoveCursor()
    {
       // Set the Current cursor, move the cursor's Position, 
       // and set its clipping rectangle to the form.  
       this.Cursor = new Cursor(Cursor.Current.Handle);
       Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);
       Cursor.Clip = new Rectangle(this.Location, this.Size);
    }

MouseMove事件恰好给了您鼠标位置。这是不包括在其他EventArgs。您可以通过Cursor.Position获取鼠标位置

静态方法Control。MousePosition将获得鼠标指针在屏幕上的绝对位置。你可以使用Control转换它。PointToClient获取感兴趣控件的本地坐标。

如果我没记错的话,一个警告是MouseEventArgs给你的鼠标位置就像消息被发布到事件循环时一样,而Control。MousePosition给出当前的位置。对于大多数应用程序,这种差异可能不是什么大问题。

您可以使用此解决方案来获取其他事件发生时图片框的坐标

protected override void OnMouseClick(MouseEventArgs e)
        {
            base.OnMouseClick(e);
            textBox1.Text = e.X.ToString();
            textBox2.Text = e.Y.ToString();
        }
       private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            textBox1.Text = e.X.ToString();
            textBox2.Text = e.Y.ToString();
        }
    } 

Or try It also

pictureBox1.MouseClick += (s, e) => MessageBox.Show(String.Format("Mouse Clicked at X: {0} Y: {1}", e.X, e.Y));