日期:2012-12-08  浏览次数:20444 次

'Module1

Option Explicit

Public Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
Public Declare Function CallWindowProc Lib "user32" Alias "CallWindowProcA" (ByVal lpPrevWndFunc As Long, ByVal hwnd As Long, ByVal uMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
Public Declare Function GetProp Lib "user32" Alias "GetPropA" (ByVal hwnd As Long, ByVal lpString As String) As Long
Public Declare Function SetProp Lib "user32" Alias "SetPropA" (ByVal hwnd As Long, ByVal lpString As String, ByVal hData As Long) As Long
Public Declare Function RemoveProp Lib "user32" Alias "RemovePropA" (ByVal hwnd As Long, ByVal lpString As String) As Long
Public Const GWL_WNDPROC = (-4&)

Public Const WM_WINDOWPOSCHANGING = &H46&

Public Type WINDOWPOS
hwnd As Long
hWndInsertAfter As Long
x As Long
y As Long
cx As Long
cy As Long
flags As Long
End Type

Public Const HWND_BOTTOM = &H1&

Public Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)

Public Function WinPropBag_ProcAddress(ByVal hwnd As Long, ByVal fStoreValue As Boolean, Optional ByVal lProcAddress As Long = 0, Optional ByVal fRemoveProp As Boolean = False) As Long
If fStoreValue Then
'保存属性
SetProp hwnd, "MY_WINPROP_PROCADDRESS", lProcAddress
Else
'取出属性
WinPropBag_ProcAddress = GetProp(hwnd, "MY_WINPROP_PROCADDRESS")
If fRemoveProp Then
'删除属性
RemoveProp hwnd, "MY_WINPROP_PROCADDRESS"
End If
End If

End Function

Public Sub Subclassing(ByVal hWndTarget As Long, Optional ByVal fUnsubclassing As Boolean = False)
If fUnsubclassing Then
WinPropBag_ProcAddress hWndTarget, True, SetWindowLong(hWndTarget, GWL_WNDPROC, AddressOf MyWindowProc)
Else
SetWindowLong hWndTarget, GWL_WNDPROC, WinPropBag_ProcAddress(hwnd:=hWndTarget, fStoreValue:=False, fRemoveProp:=True)
End If
End Sub

Public Function MyWindowProc(ByVal hwnd As Long, ByVal uMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
If uMsg = WM_WINDOWPOSCHANGING Then
'可以这样写
Dim ut As WINDOWPOS
CopyMemory ut, ByVal lParam, Len(ut)
ut.hWndInsertAfter = HWND_BOTTOM
CopyMemory ByVal lParam, ut, Len(ut)
'也可以这接这样写
'CopyMemory ByVal lParam + 4, HWND_BOTTOM, 4
End If
MyWindowProc = CallWindowProc(WinPropBag_ProcAddress(hwnd, False), hwnd, uMsg, wParam, lParam)
End Function


'Form1

Private Sub Form_Load()
Subclassing Me.hwnd, True
End Sub

Private Sub Form_Unload(Cancel As Integer)
Subclassing Me.hwnd, False
End Sub