分享

VB的鼠标离开事件实现

 星星点点灯 2017-03-02
 在VB中,几乎所有控件都提供了MouseMove、MouseDown、MouseUp、Click、DblClick这些鼠标操作事件,却惟独没有MouseLeave事件,而鼠标离开事件在一些应用中可以使我们的程序更显智能化或更显动态变换性。例如:当鼠标移动到某一控件时,就跳出一个帮助小精灵,当鼠标离开该控件时,小精灵即自动消失。
其实借助2个API函数和MouseMove事件,很容易就捕捉到MouseLeave事件,也就可以轻松实现上面的开、关小精灵功能。下面就是实现该功能的原代码:
在窗体头部说明API函数: 


Private Declare Function SetCapture Lib "user32" (ByVal hWnd As Long) As Long
Private Declare Function ReleaseCapture Lib "user32" () As Long 


下面是控件Object1的MouseMove事件中代码: 


Private Sub Object1_MouseMove(Button As Integer, Shift As Integer, As Single, As Single)
Dim MouseOver As Boolean

'判断当前鼠标位置是否在Object1上
MouseOver (0 <= X) And (X <= Object1.Width) And (0 <= Y) And (Y <= Object1.Height)
If MouseOver Then
MouseOver Event
假如鼠标在Object1上, 则利用SetCapture将每一个鼠标事件都传递给Object1
并显示小精灵
小精灵.Visible True
SetCapture Object1.hWnd
Else
MouseLeave Event
假如鼠标不在Object1上, 则利用ReleaseCapture释放鼠标捕捉
并关闭显示小精灵
小精灵.Visible False
ReleaseCapture
End If
End Sub 


另,这个方法只是针对有HWND 的控件,如果是label等就不行了。请问一下,有没有label之类控件的鼠标离开的方法呢?

Option Explicit

Private Declare Function SetCapture Lib "user32" (ByVal hWnd As Long) As Long
Private Declare Function ReleaseCapture Lib "user32" () As Long

'通过Form的MouseMove事件,处理无句柄控件(Label、Image等)的鼠标离开事件
Private Sub Form_MouseMove(Button As Integer, Shift As Integer, As Single, As Single)
Dim MouseOver As Boolean
'判断当前鼠标位置是否在Label1上
MouseOver (Label1.Left <= X) And (X <= Label1.Left Label1.Width) And (Label1.Top <= Y) And (Y <= Label1.Top Label1.Height)
If MouseOver Then '鼠标位置是在Label1上
MouseOver Event
Label1.Visible True '显示Label1
If Button Then '如果鼠标键没有按下则利用SetCapture将每一个鼠标事件都传递给Form1
SetCapture Form1.hWnd
End If
Else
MouseLeave Event
Label1.Visible False '关闭显示Label1
ReleaseCapture 假如鼠标不在Label1上, 则利用ReleaseCapture释放鼠标捕捉
End If
End Sub

'当Label1响应过鼠标事件后,再次判别鼠标位置
Private Sub Label1_MouseUp(Button As Integer, Shift As Integer, As Single, As Single)
Dim MouseOver As Boolean
MouseOver (Label1.Left <= X) And (X <= Label1.Left Label1.Width) And (Label1.Top <= Y) And (Y <= Label1.Top Label1.Height)
If MouseOver Then '鼠标位置是在Label1上
MouseOver Event
Label1.Visible True '显示Label1
SetCapture Form1.hWnd '利用SetCapture将每一个鼠标事件都传递给Form1
Else
MouseLeave Event
Label1.Visible False '关闭显示Label1
ReleaseCapture 假如鼠标不在Label1上, 则利用ReleaseCapture释放鼠标捕捉
End If
End Sub

'程序退出时释放鼠标捕捉
Private Sub Form_Unload(Cancel As Integer)
ReleaseCapture
End Sub 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多