VB.net — Getting mouse coordinates outside the for

2019-07-03 23:20发布

问题:

I'm writing a simple program in Vb.net that collects information. such things as mouse x y coordinates, Pixel color, and keystroke numbers. I would like to be able to view the x and y coordinates of the cursor anywhere on the screen instead of just over the form, and i would like to do this in the simplest way possible. One way i have achieved the desired effect is with the following settings:

Picturebox2:

  • BackColor = Red
  • image = 3 x 2 pixel image (Hardly visible, but is required all the same)

Form1:

  • Transparency key = Red

This results in the appearance of the mouse coordinates being displayed while the cursor is outside the form boundaries. however it's still over the form. The code i'm using for this particular problem is:

Dim mouseloc As Point


Private Sub Form1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseMove
    mouseloc = Cursor.Position
    lblc.Text = PointToClient(mouseloc).ToString
    lbls.Text = PointToScreen(mouseloc).ToString
End Sub

Private Sub PictureBox2_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox2.MouseMove
    mouseloc = Cursor.Position
    lblc.Text = PointToClient(mouseloc).ToString
    lbls.Text = PointToScreen(mouseloc).ToString
End Sub

Im running Visual Studio 2010 on a Windows 7 x64 Sony VAIO

回答1:

A really simple way would be to Capture the mouse in the Form via Me.Capture = True. See here for details:

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.capture.aspx

That being said, if you need to track the mouse even when you are not the active application you are going to have to use some type of hooking. Not clear exactly what you are looking to do though.