DataGrid控件如何才能支持鼠标滚轮呢?谢谢!
DataGrid本身不支持鼠标滚轮功能,必须要通过API才能实现。
下面代码,无论你的窗体有多少个DataGrid控件,只要是获得焦点的就支持鼠标滚轮,而且还支持MSHFlexGrid控件鼠标滚轮!
代码如下:
一、先建一个模块(Module1),把以下代码贴上:
Option Explicit
Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long) As Long
Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
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
Private Const GWL_WNDPROC = (-4)
Private Const WM_MOUSEWHEEL = &H20A
Private lpWndProc As Long
Public Sub Hook(hwnd As Long)
lpWndProc = GetWindowLong(hwnd, GWL_WNDPROC) '获得原始窗口函数句柄
SetWindowLong hwnd, GWL_WNDPROC, AddressOf WindowProc '装载WM_MOUSEWHEEL消息的处理过程到窗口函数
End Sub
Public Sub UnHook(hwnd As Long)
SetWindowLong hwnd, GWL_WNDPROC, lpWndProc '御掉Hook,还原原始窗口函数
End Sub
Private Function WindowProc(ByVal hwnd As Long, ByVal uMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
'处理WM_MOUSEWHEEL消息的窗口函数
Dim wzDelta As Integer
If uMsg = WM_MOUSEWHEEL Then
wzDelta = HIWORD(wParam)
If Sgn(wzDelta) = 1 Then
If TypeOf Screen.ActiveControl Is DataGrid Then Screen.ActiveControl.Scroll 0, -1
Else
If TypeOf Screen.ActiveControl Is DataGrid Then Screen.ActiveControl.Scroll 0, 1
End If
If TypeOf Screen.ActiveControl Is MSHFlexGrid Then
If wzDelta > 0 Then
If Screen.ActiveControl.TopRow > 1 Then
If Screen.ActiveControl.TopRow < 1 Then
Screen.ActiveControl.TopRow = 1
Else
Screen.ActiveControl.TopRow = Screen.ActiveControl.TopRow - 1
End If
End If
Else
If Screen.ActiveControl.TopRow < Screen.ActiveControl.Rows Then
Screen.ActiveControl.TopRow = Screen.ActiveControl.TopRow + 1
End If
End If
End If
End If
WindowProc = CallWindowProc(lpWndProc, hwnd, uMsg, wParam, lParam)
End Function
Private Function HIWORD(MsgParam As Long) As Integer
'取出32位值的高16位
HIWORD = (MsgParam And &HFFFF0000) \ &H10000
End Function
二、在工程调用函数:
Private Sub Form_Load()
Call Hook(Me.hwnd)
End Sub
Private Sub Form_Unload(Cancel As Integer)
Call UnHook(Me.hwnd)
End Sub
注:DataGrid在编辑状态下是不能滚动的,必须在选择(某行)状态下才能滚动。
※※※以上的方法在vb.net中怎么实现?请高人指点,Screen.ActiveControl 对应的VB.net怎么修改。