【VB】VB的鼠标离开事件实现
VB的鼠标离开事件实现(转)在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, X As Single, Y 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, X As Single, Y 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 = 0 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, X As Single, Y 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
附:判断鼠标是否在窗体上的方法:
Private Declare Function SetCapture Lib "user32" (ByVal hWnd As Long) As Long
Private Declare Function ReleaseCapture 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 And X < .Width And Y > 0 And Y < .Height Then
SetCapture Me.hWnd
Label1 = "进入"
Else
ReleaseCapture
Label1 = "离开"
End If
End With
End Sub
文本转载自某人空间,若侵犯了权益,请联系我,积极删除。 不错,楼主,啥时候弄一个c/s的vb源代码呢? anyscai 发表于 2017-7-19 07:51
不错,楼主,啥时候弄一个c/s的vb源代码呢?
目前没有能力编写这些高级东西,只会用基本语法,拿来收藏用。 貌似有自带的这个功能吧 这是 VB6 的代码么,还是 VB.Net 的 我很赞同!
页:
[1]