How do you detect the mouses movement with out using a mouse event in a form or any other thing in the tool bar in vb?
Printable View
How do you detect the mouses movement with out using a mouse event in a form or any other thing in the tool bar in vb?
You can use the GetCursorPos API function to get the cursor position from anywhere on the screen (not just over your form or controls).
Here is a sample project:
- Start a new VB project
- Add a standard module (Module1)
- Add 2 labels to your form (Label1 and Label2)
- Add a timer to your form (Timer1)
- Set the timer Interval property to 1
- Paste the first section of code into the Module
- Paste the second section of code into the form's code window
- Run the project and move the mouse around!
Here is the code for the Module:
Here is the code for the form's code window:Code:Option Explicit
Type POINTAPI
x As Long
y As Long
End Type
Declare Function GetCursorPos Lib "user32" _
(lpPoint As POINTAPI) As Long
Hope that helps!Code:Option Explicit
Private Sub Form_Load()
'This just sets up the form and controls (not really necessary)
With Me
.Caption = "Cursor Position"
.Width = 2750
.Height = 1500
.left = (Screen.Width - .Width) / 2
.top = (Screen.Height - .Height) / 2
End With
With Label1
.Alignment = vbCenter
.Width = 1750
.Height = 300
.left = (Me.ScaleWidth - .Width) / 2
.top = 100
End With
With Label2
.Alignment = vbCenter
.Width = Label1.Width
.Height = Label1.Height
.left = Label1.left
.top = Label1.top + Label1.Height + 100
End With
End Sub
Private Sub Timer1_Timer()
'This is the real meat of the program...not too difficult!
Dim CursorPos As POINTAPI
GetCursorPos CursorPos 'Assigns cursor's x and y to CursorPos
Label1 = "Cursor X = " & CursorPos.x
Label2 = "Cursor Y = " & CursorPos.y
End Sub
~seaweed