All Snippets
Top 100 Snippets

By Language

GBIC >> Source Code >> Visual Basic >> Snippet

30 Subclassing

'The Windows Operating System (OS) manages the various windows of your applications.
'Each window is given a unique id number (windows handle, also known as hWnd).  The
'OS continually monitors these windows for signs of activity or events - such as a mouse
'click or button press.  When an event occurs the OS determines which window(s) it affects
'and sends a message to those windows.  The windows respond according to the code
'the programmer has included in the project that contains those windows.

'VB either handles the message for you, or it exposes the message to you as an Event
'procedure, which is where you put your code to respond to the event.

'Each window has a message handler - code that will respond to the OS message.
'The message handler is called a WindowProc - short for window procedure.

'When a window is subclassed, you write a new window procedure that is inserted
'between the OS and the original window procedure.  

'Your new procedure is responsible for deciding which messages to handle or which
'messages you want to pass on to the default WindowProc.

'Example of a custom WindowProc - put this in a .BAS module!
Public Declare Function CallWindowProc& Lib "user32" Alias "CallWindowProcA" ( ByVal lpPrevWndFunc&, ByVal hWnd&, ByVal Msg&, ByVal wParam&, ByVal lParam&)
Public Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" ( ByVal hWnd&, ByVal nIndex&, ByVal dwNewLong&) As Long
Const GWL_WNDPROC = - 4
Public lpPrevWindowProc As Long

Public Function WindowProc( ByVal hWnd As Long , ByVal iMsg As Long , ByVal wParam As Long , ByVal lParam As Long ) As Long
'this is the WindowProc that will be used to reply to Windows messages - takes over for the original WindowProc
   If iMsg = TargetMessage
        'do something of our own
       WindowProc = 0&
        Exit Function               ' exit the function - preventing VB from getting the message  - delete this to let both WindowProc run
   End If
  'pass all other messages on to VB and then return the value to Windows
 WindowProc = CallWindowProc(lpPrevWindowProce, hWnd, iMsg, wParam, lParam)     'passes parameters unchanged to original Windows message handler
End Function

'in load event of form, take over control of messages - save pointer to the original WindowProc
lpPrevWindowProc = SetWindowLong(hWnd, GWL_WNDPROC, AddressOf WindowProc)          'this is a CallBack

'in unload event of form - return control to the original WindowProc
Call SetWindowLong(hWnd, GWL_WNDPROC, lpPrevWindowProc)