Question How to obtain mouse co-ordinates over items?

MaxVB

New member
Joined
Feb 7, 2012
Messages
1
Programming Experience
1-3
Hey, I've been lurking on this forum for a while but only needed to post today. For my program I need to be able to get the mouse co-ordinates in order to make labels draggable. I am currently using this code:

Private Sub Form1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseMove
Label1.Text = "X." & e.X & vbCrLf & "Y." & e.Y
End Sub

which works, but not when the mouse is over a button, image etc, it only works when it's over the actual form. Is there a way to make it get the mouse position at any point?

Thanks a lot for any help! :D
 
A possible alternative is to get the coordinates of the mouse on the screen, get the coordinates of the top left corner of the form, and subtract the one from the other.
 
The problem is that you're only handling the event of the form, not of its child controls. If you want feedback when the mouse is over any control then you need to handle the event of every control. In that case though, you'll be getting the mouse coordinates relative to that control, not the form. If you always want form coordinates then you will have to do a bit of translation, e.g.
Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim ctl = GetNextControl(Me, True)

        Do Until ctl Is Nothing
            AddHandler ctl.MouseMove, AddressOf Form1_MouseMove
            ctl = GetNextControl(ctl, True)
        Loop
    End Sub

    Private Sub Form1_MouseMove(sender As Object, e As MouseEventArgs) Handles Me.MouseMove
        Dim formCoords = PointToClient(Cursor.Position)

        Label1.Text = formCoords.ToString()
    End Sub

End Class
 
Back
Top