'如何用VB判斷鼠標在不在窗體內?
'給窗體上添加一個timer控件
Option Explicit
Private Type POINTAPI
X As Long
Y As Long
End Type
Private MouseXY As POINTAPI
Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
Private Sub Form_Load()
Timer1.Interval = 200 '每200毫秒執行判斷一次鼠標位置
Timer1.Enabled = True
End Sub
Private Sub Timer1_Timer()
GetCursorPos MouseXY
MouseXY.X = MouseXY.X * 15
MouseXY.Y = MouseXY.Y * 15
If MouseXY.X > Me.Left And MouseXY.X < Me.Left + Me.Width And MouseXY.Y > Me.Top And MouseXY.Y < Me.Top + Me.Height Then '如果鼠標在窗口內
'如果鼠標在窗體范圍內執行下面的代碼
Me.Caption = "在窗體內"
Print "在窗體內"
Else
'如果鼠標不在窗體上,則執行下面的代碼
Me.Caption = "在窗體外"
Print "在窗體外"
End If
End Sub
'++++++++++一點簡單的例子++++++++
'這個例子是用來:鼠標移到窗體上后顯示窗體下部隱藏的3000高度的內容,鼠標離開后再自動隱藏
Private Sub Timer1_Timer()
GetCursorPos MouseXY
MouseXY.X = MouseXY.X * 15
MouseXY.Y = MouseXY.Y * 15
If MouseXY.X > Me.Left And MouseXY.X < Me.Left + Me.Width And MouseXY.Y > Me.Top And MouseXY.Y < Me.Top + Me.Height Then '如果鼠標在窗口內
If Form1.Height < 4000 Then '如果窗體高度小于4000
Form1.Height = Form1.Height + 3000 '高度加3000
End If
Else
If Form1.Height > 3000 Then ’如果窗體高度大于3000
Form1.Height = Form1.Height - 3000 '高度減3000
End If
End If
End Sub
'++++++++++例子結束++++++++
-------------另VB判斷鼠標是否離開command控件的VB代碼---------
Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
Command1.Caption = X + Y '這句可以不要 ,只是用來調試
Call command1_mouseleave(X - Y) '函數里可以不傳變量 相應的你下面的函數體里也可以不用變量
End Sub '如果有多個控件,這段程序要在除了你的那個按鈕控件以外的所有控件里出現
Private Sub command1_mouseleave(a As Integer)
Me.Caption = a '在這里添加鼠標離開程序,我這句只是驗證是否執行了
End Sub