I was planning this post anyway, when someone on the vbCity forums was looking for some very similar code. She wanted to keep track of where the mouse cursor was, relative to the position on a PictureBox. And then she wanted to position another visual element relative to the form. This is sort of a screenshot, but for some reason it's missing the mouse cursor. (It was just above the top left of the yellow box.)
The visual element uses a Label control (the coordinate text) on a Panel (the yellow box). As the mouse moves, the Panel follows just below it, adjusting itself for the edge of the form.
Here's the code, which I believe is pretty self-explanatory. The main hurdle is PointToClient, which gives a pair of coordinates relative to the form or control it references. If you want position relative to the monitor size, use Screen. When a form is maximized, Screen and form are almost, but not exactly equivalent. BringToFront() is necessary, because otherwise the panel positions itself behind the PictureBox.
Sub PictureBox1_MouseDown(ByVal sender As ...
Panel1.Visible = True
ShowPanel()
End Sub
Private Sub PictureBox1_MouseMove(ByVal sender As System.Object, ByVal e As ...
ShowPanel()
End Sub
Private Sub PictureBox1_MouseUp(ByVal sender As System.Object, ByVal e As ...
Panel1.Visible = False
End Sub
Private Sub ShowPanel()
Dim pPic As Point = PictureBox1.PointToClient(MousePosition)
Label1.Text = pPic.X.ToString() + ", " + pPic.Y.ToString()
Dim pPan As Point = Me.PointToClient(Me.MousePosition)
pPan.X += 2
pPan.Y += 2
If (pPan.X + Panel1.Width > Me.Width) Then pPan.X = pPan.X - Panel1.Width - 4
If (pPan.Y + Panel1.Height > Me.Height) Then pPan.Y = pPan.Y - Panel1.Height - 4
Panel1.Location = pPan
Panel1.BringToFront()
End Sub
The article I was planning to write was actually about the DataGridView, and I was going to position the Panel relative to the keyboard cursor, not the mouse cursor. I used the CellEnter event, the CurrentCell property and the GetCellDisplayRectangle method to figure out where I was. Otherwise, the idea is pretty much the same.