Determine If Mouse Is Within Your Form
This is to know whether the user has the mouse over your form or outside of it...Might be useful for people so... Enjoy :wave:
VB Code:
'API AND DECLARATIONS
Private Type POINTAPI
x As Long
y As Long
End Type
Private Declare Function GetCursorPos Lib "user32.dll" (ByRef lpPoint As POINTAPI) As Long
'==========================================================
Private Function MouseInForm(pForm As Form) As Boolean
Dim iRight As Long
Dim iLeft As Long
Dim iBottom As Long
Dim iTop As Long
Dim PT As POINTAPI
'Lets convert everything to pixels since that's what GetCursorPos returns...
iRight = (pForm.Left + pForm.Width) / Screen.TwipsPerPixelX
iBottom = (pForm.Top + pForm.Height) / Screen.TwipsPerPixelY
iLeft = pForm.Left / Screen.TwipsPerPixelX
iTop = pForm.Top / Screen.TwipsPerPixelY
GetCursorPos PT
If (PT.x <= iRight) And (PT.x >= iLeft) _
And (PT.y >= iTop) And (PT.y <= iBottom) Then
MouseInForm = True
Else
MouseInForm = False
End If
End Function
'USAGE:
'Can be used in Form_Mousemove or a Timer or anywhere you want to check if mouse is in your form
If MouseInForm(frmMain) Then
MsgBox "Mouse currently over frmMain"
Else
MsgBox "Mouse is not over frmMain"
End If
Re: Determine If Mouse Is Within Your Form
Where would you put your usage code? BTW, it looks like you don't use Option Explicit becuse you have Dim iButtom As Long
Re: Determine If Mouse Is Within Your Form
Quote:
Originally Posted by MartinLiss
Where would you put your usage code? BTW, it looks like you don't use Option Explicit becuse you have Dim iButtom As Long
Thanks for that martin :) i fixed it and added where to use it...
Re: Determine If Mouse Is Within Your Form
Very nice example EJ12N! Helped me on my last project!
:) :) :) :) :) :) :) :) :) :) :) :) :) :) :) :) :) :)
Re: Determine If Mouse Is Within Your Form
Another way :
VB Code:
Option Explicit
Private Declare Function SetCapture Lib "user32" (ByVal hwnd As Long) As Long
Private Declare Function ReleaseCapture Lib "user32" () As Long
Private Declare Function GetCapture Lib "user32" () As Long
Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
With Me
If (X < 0) Or (Y < 0) Or (X > .Width) Or (Y > .Height) Then 'MouseLeave
Call ReleaseCapture
Debug.Print "Off"
ElseIf GetCapture() <> .hwnd Then 'MouseEnter
Call SetCapture(.hwnd)
Debug.Print "On"
Else
'Normal MouseMove
End If
End With
End Sub
Re: Determine If Mouse Is Within Your Form