vb.netwinformsscreen-resolutionwindows-controls

Find position of mouse relative to control, rather than screen


I have a Picture Box called BGImage. I hope that when the user clicks on this I can capture the position of the mouse relative to BGImage.

I've tried using MousePosition, only to find it gives the mouse location on the screen, not on the PictureBox.

So I also tried using PointToClient:

Dim MousePos As Point = Me.PointToClient(MousePosition)

But this gives me the location {X=1866,Y=55} whereas I actually clicked on the PictureBox at around {X=516,Y=284}.

I think the problem arises because I have full-screened my program and set the position of the PictureBox to be at the centre of the screen (BGImage.Location = New Point((My.Computer.Screen.WorkingArea.Width / 2) - (1008 / 2), ((My.Computer.Screen.WorkingArea.Height / 2) - (567 / 2))))

I should also mention that the size of the PictureBox is 1008 By 567 pixels and my screen resolution is 1366 by 768.

Is there any way I can get the mouse position relative to BGImage's position?


Solution

  • Add a mouse click event to your picture box
    Then use the MouseEventArgs to get the mouse position inside the picture box.
    This will give you the X and the Y location inside the picture box.

    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