楼主 amulee |
Q:如何给ListView添加滚动条事件? A:ListView控件是不具备滚动条事件的,但是可以通过子类化来捕捉滚动条事件从而实现事件程序的触发。 在Windows的机制中,各项操作都是通过消息来发送指令完成的。 当单击ListView滚动条时,系统会自动发送相应的消息(长整形变量)给指定窗口函数,该函数根据发送来的消息得知不同的操作,从而进行相应的操作。 子类化就是在消息发送给默认的窗口函数之前拦截这个消息,编程者可以利用发送来的消息决定自己的操作。
本例就是通过子类化拦截ListView发送来的消息,当消息是处理垂直滚动条时,则调用自己定义的事件程序。 参考代码如下: 添加一个模块:
- '调用指定窗口函数的API函数定义
- 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
- '设置Windows长参数的API函数定义
- Public Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" _
- (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
- Public Const WM_VSCROLL As Long = &H115 '滚动条事件
- Public lpPrevWndProc As Long '存放原窗口函数句柄
- Public Const GWL_WNDPROC As Long = (-4) '指定替换原窗口函数常数
- '我们自己的窗口函数
- Public Function ListViewWindowProc(ByVal hwnd As Long, ByVal uMsg As Long, _
- ByVal wParam As Long, ByVal lParam As Long) As Long
- '应用程序可在此截获所需的Windows消息加以处理
- If uMsg = WM_VSCROLL Then '消息为垂直滚动条发送来的则触发
- '调用自定义的事件
- Call UserForm1.ListView_VScroll(ByVal wParam)
- End If
- '调用原窗口函数,由原窗口函数处理Windows消息
- ListViewWindowProc = CallWindowProc(lpPrevWndProc, hwnd, uMsg, wParam, lParam)
- End Function
- Sub Test()
- UserForm1.Show
- End Sub
窗体代码如下:
- Private Sub UserForm_Initialize()
- Dim i As Integer
- '添加数据
- With ListView1
- .ColumnHeaders.Add , , "Column 1"
- .View = lvwReport
- For i = 1 To 1000
- .ListItems.Add , , "Item " & CStr(i)
- Next
- End With
- '子类化
- '设置ListView1的新窗口函数为ListViewWindowProc,将原窗口函数地址送lpPrevWndProc
- lpPrevWndProc = SetWindowLong(ListView1.hwnd, GWL_WNDPROC, AddressOf ListViewWindowProc)
- End Sub
- Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
- Dim Temp As Long
- '恢复原窗口函数
- Temp = SetWindowLong(ListView1.hwnd, GWL_WNDPROC, lpPrevWndProc)
- End Sub
- '自定义的滚动条事件
- Sub ListView_VScroll(ByVal Direction As Long)
- Select Case Direction
- Case 3, 1
- MsgBox "向下滚动"
- Case 0, 2
- MsgBox "向上滚动"
- End Select
- End Sub
附件下载: 用子类化实现ListView滚动条事件.rar |