【问题标题】:Find position of mouse relative to control, rather than screen查找鼠标相对于控件的位置,而不是屏幕
【发布时间】:2015-02-15 20:56:07
【问题描述】:

我有一个名为 BGImage 的图片框。我希望当用户点击它时,我可以捕捉到鼠标相对于BGImage的位置。

我尝试使用MousePosition,却发现它在屏幕上给出了鼠标位置,而不是在图片框上。

所以我也尝试使用PointToClient:

Dim MousePos As Point = Me.PointToClient(MousePosition)

但这给了我{X=1866,Y=55} 的位置,而我实际上点击了{X=516,Y=284} 附近的图片框。

我认为问题的出现是因为我已经全屏显示了我的程序并将 PictureBox 的位置设置在屏幕的中心 (BGImage.Location = New Point((My.Computer.Screen.WorkingArea.Width / 2) - (1008 / 2), ((My.Computer.Screen.WorkingArea.Height / 2) - (567 / 2))))

我还应该提到 PictureBox 的大小是 1008 × 567 像素,我的屏幕分辨率是 1366 × 768。

有什么方法可以让鼠标位置相对相对于 BGImage 的位置?

【问题讨论】:

    标签: vb.net winforms screen-resolution windows-controls


    【解决方案1】:

    为您的图片框添加鼠标点击事件
    然后使用 MouseEventArgs 获取图片框内的鼠标位置。
    这将为您提供图片框内的 X 和 Y 位置。

    Dim PPoint As Point
    Private Sub PictureBox1_MouseClick(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseClick
        PPoint = New Point(e.X, e.Y)
        MsgBox(Convert.ToString(PPoint))
    End Sub
    

    【讨论】:

      【解决方案2】:

      我之前遇到过同样的问题,只是在一些朋友的帮助下解决了。 看这里mouse position is not correct 这是根据图片为您提供鼠标正确位置的代码。 坦克@Aaron 他已经给出了这个问题的最终解决方案。

      这将在您单击的确切点上放置一个红点。我想知道设置光标位置会有多大用处,因为它们几乎肯定会在单击按钮后移动鼠标(无论是否无意)。

      设置光标位置需要在屏幕坐标中 - 这将转换回客户端坐标以进行绘图。我不相信 PointToClient 对于光标位置是必需的。在下面的代码中,这是不必要的转换,因为您只是返回到客户端坐标。我把它留下来展示每个转换的示例,以便您可以对它们进行试验。

      Public Class Form1
      Private PPoint As Point
      Public Sub New()
      
      ' This call is required by the designer.
      InitializeComponent()
      PictureBox1.BackColor = Color.White
      PictureBox1.BorderStyle = BorderStyle.Fixed3D
      AddHandler PictureBox1.MouseClick, AddressOf PictureBox1_MouseClick
      AddHandler Button8.Click, AddressOf Button8_Click
      ' Add any initialization after the InitializeComponent() call.
      
      End Sub
      
      Private Sub Button8_Click(sender As Object, e As EventArgs)
      Dim g As Graphics = PictureBox1.CreateGraphics()
      Dim rect As New Rectangle(PictureBox1.PointToClient(PPoint), New Size(1, 1))
      g.DrawRectangle(Pens.Red, rect)
      End Sub
      
      Private Sub PictureBox1_MouseClick(sender As Object, e As MouseEventArgs)
      PPoint = PictureBox1.PointToScreen(New Point(e.X, e.Y))
      Label8.Text = PPoint.X.ToString()
      Label9.Text = PPoint.Y.ToString()
      
      End Sub
      End Class
      

      【讨论】:

      • 我实际上之前尝试过这个,它不正确链接上的那个它正确我已经准备好了尝试
      【解决方案3】:

      而不是使用:

      Dim MousePos As Point = Me.PointToClient(MousePosition)
      

      你应该使用:

      Dim MousePos As Point = BGImage.PointToClient(MousePosition)
      

      它将为您提供 BGImage 坐标中的鼠标位置,而第一个代码为您提供窗体坐标中的鼠标位置。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-30
        • 2011-03-15
        • 2015-04-08
        • 1970-01-01
        • 2021-10-14
        • 2011-06-27
        相关资源
        最近更新 更多