在VB中处理鼠标滚轮事件源代码
本人在上次编制Smart Bar ActiveX Control 1.0中使用了鼠标滚轮事件。现在将这部分代码拿出来,做成一个简单的例子,以便网友们使用。1.首先在Module中定义如下函数和变量:
Option Explicit
Public Declare Function CallWindowProc Lib "user32" Alias "CallWindowProcA" (ByVal lpPrevWndFunc As Long, ByVal hwnd As Long, ByVal Msg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long<BR>Public Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long) As Long<BR>Public Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long<BR>Public Const GWL_WNDPROC = -4&<BR>Public Const WM_MOUSEWHEEL = &H20A
Public Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long<BR>Public Declare Function WindowFromPoint Lib "user32" (ByVal xPoint As Long, ByVal yPoint As Long) As Long<BR>Public Type POINTAPI<BR> x As Long<BR> y As Long<BR>End Type
Public OldWindowProc As Long '用来保存系统默认的窗口消息处理函数的地址<BR>Public hwndTextBox As Long '用来保存Text1控件的句柄
'自定义的消息处理函数<BR>Public Function NewWindowProc(ByVal hwnd As Long, ByVal Msg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long<BR> On Error Resume Next<BR> If Msg = WM_MOUSEWHEEL Then<BR> '下面得到鼠标位置处的对象的句柄<BR> Dim CurPoint As POINTAPI, hwndUnderCursor As Long<BR> GetCursorPos CurPoint<BR> hwndUnderCursor = WindowFromPoint(CurPoint.x, CurPoint.y)<BR> '如果鼠标位于Form1.Text1内部,则对鼠标滚轮事件进行处理<BR> If hwndUnderCursor = hwndTextBox Then<BR> If wParam = -7864320 Then '向下滚动<BR> Form1.Text1 = CInt(Form1.Text1) - 1<BR> ElseIf wParam = 7864320 Then '向上滚动<BR> Form1.Text1 = CInt(Form1.Text1) + 1<BR> End If<BR> End If<BR> Else<BR> '调用Text1的默认窗口消息处理函数<BR> NewWindowProc = CallWindowProc(OldWindowProc, hwnd, Msg, wParam, lParam)<BR> End If<BR>End Function
2.在Form页面上放置一个Text1控件,在Form_Load事件中写入如下代码:<BR>Private Sub Form_Load()<BR> Text1 = 0<BR> '取得Text1控件的句柄<BR> hwndTextBox = Text1.hwnd<BR> '保存Text1控件的默认窗口消息处理函数地址<BR> OldWindowProc = GetWindowLong(Text1.hwnd, GWL_WNDPROC)<BR> '将Text1控件的消息处理函数指定为自定义函数NewWindowProc<BR> Call SetWindowLong(Text1.hwnd, GWL_WNDPROC, AddressOf NewWindowProc)<BR> <BR>End Sub
3.运行,在Text1控件上面滚动鼠标滚轮,就可以发现Text的文本发生相应改变。
附件为源代码。
谢谢,如果能说明详细点就更好了!
页:
[1]