子分類技術的原理:要先取得原先Window Procedure所在的地址,將之記錄起來,接著設定所有的消息都先轉到我們所寫的消息處理過程上來,我們過濾傳過來的消息,尋找特定的消息進行處理,其余的送回系統,由系統決定如何處理。等到我們不需要再處理這些特定的消息時,便取消消息的截取,即中止子分類過程。它一般需要三個過程:開始截取,消息處理,中止截取.
程序需要一個模塊,在模塊中聲明如下:
'API函數Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" _
(ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) A s Long Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" _
(ByVal hwnd As Long, ByVal nIndex 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
'定義常數Public Const GWL_WNDPROC = (-4) Public Const WM_MOUSEMOVE = &H200 Public Const WM_RBUTTONDOWN = &H204
'全局變量,存放控件標志性數據Public preWinProc As Long
'本函數就是用來接收子分類時截取的消息的Public Function wndproc(ByVal hwnd As Long, ByVal Msg As Long, _
ByVal wParam As Long, ByVal lParam As Long) As
Long
'截取下來的消息存放在msg參數中.
if msg=WM_RBUTTONDOWN then
'檢測到鼠標右擊消息,這裡就可以加入我們的處理代碼如:
msgbox "你好,鼠標右擊消息!"
'需要注意,如果這兒不加入任何代碼,則相當於吃掉了這條消息. else
'如果我們不是我們需要處理的消息,則將之送回原來的程序.
wndproc = CallWindowProc(preWinProc, hwnd, Msg, wParam, lParam) endif End Function
'以下代碼在窗體中: '本例以截取一個combobox控件的消息為例,假設該'控件的名字是:comb1 Private Sub subclass() Dim ret As Long
'記錄Window Procedure的地址
preWinProc = GetWindowLong(comb1.hwnd, GWL_WNDPROC)
'開始截取消息,並將消息交給wndproc過程處理.
ret = SetWindowLong(comb1.hwnd, GWL_WNDPROC, AddressOf wndproc) End Sub
Private Sub EndSubclass()
Dim ret As Long
'取消消息截取,結束子分類過程.
ret = SetWindowLong(comb1.hwnd, GWL_WNDPROC, preWinProc) End Sub
'當要截取其它控件的消息時,只需要將subclass與EndSubclass過程中的comb1.h wnd換成該控件的控件.hwnd即可. '調試過程中注意存盤,因為如果一時不慎會造成死機。