如果程序里面有多个窗体,每个窗体包含多个MSFlexGrid控件,使用这种办法比单独为每个网格控件编写代码方便一些
用文本替换把“MSFlexGrid”替换为“MSHFlexGrid”就可以支持MSHFlexGrid控件了
新建一个模块,贴上下面的代码:Public Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As LongPublic 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 LongPublic Const GWL_WNDPROC = (-4)
Public Type tGridList frm As Form grid As MSFlexGrid grdHwnd As Long grdPreProc As LongEnd Type
Private GridList() As tGridListPrivate nGridCount As Long
Public Function WindowProcGridHook(ByVal hwnd As Long, ByVal uMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long Dim nIndex As Long nIndex = GetGridIndex(hwnd) If uMsg <> 522 Then WindowProcGridHook = CallWindowProc(GridList(nIndex).grdPreProc, hwnd, uMsg, wParam, lParam) Else '滚轮 On Error Resume Next With GridList(nIndex).grid Dim lngTopRow As Long, lngBottomRow As Long lngTopRow = 1 lngBottomRow = .Rows - 1 If wParam > 0 Then If Not .RowIsVisible(lngTopRow) Then .TopRow = .TopRow - 1 End If Else .TopRow = .TopRow + 1 End If End With End IfEnd Function
Public Sub StartHook(frm As Form) Dim x As Variant Dim proc As Long For Each x In frm.Controls If TypeOf x Is MSFlexGrid Then nGridCount = nGridCount + 1 ReDim Preserve GridList(1 To nGridCount) As tGridList Set GridList(nGridCount).grid = x Set GridList(nGridCount).frm = frm GridList(nGridCount).grdHwnd = x.hwnd proc = SetWindowLong(x.hwnd, GWL_WNDPROC, AddressOf WindowProcGridHook) GridList(nGridCount).grdPreProc = proc End If NextEnd Sub
Public Sub EndHook(frm As Form) Dim i As Long, j As Long, n As Long For i = nGridCount To 1 Step -1 If GridList(i).frm Is frm Then SetWindowLong GridList(i).grdHwnd, GWL_WNDPROC, GridList(i).grdPreProc n = n + 1 For j = i To nGridCount - n GridList(j) = GridList(j + 1) Next End If Next nGridCount = nGridCount - nEnd Sub
Private Function GetGridIndex(hwnd As Long) As Long Dim i As Long For i = 1 To nGridCount If GridList(i).grdHwnd = hwnd Then GetGridIndex = i Exit Function End If NextEnd Function
然后在每个包含MSFlexGrid控件的窗体调用StartHook和EndHook这两个过程例如:Private Sub Form_Load() StartHook MeEnd SubPrivate Sub Form_Unload(Cancel As Integer) EndHook MeEnd Sub这样就可以支持滚轮了
