Eldritch Coding Horrors, Part 1

I found this terror today in a legacy application.

Program A uses SetWindowLong to hook the message loop for a Windows Form:


Friend Function StartListening() As Boolean
SetWindowLong(m_MappedWndHandle, GWL_WNDPROC, AddressOf WindowProcedure)
End Function

Program A then shells program B. Program B sends a WM_COPYDATA message to program A. Program A intercept the message, reads the data, and then passes the message to the form:


Public Function WindowProcedure(ByVal hwnd As Long, ByVal msg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
If msg = WM_COPYDATA Then
objMapMemoryData.ReadMessage lParam
End If
WindowProcedure = CallWindowProc(objMapMemoryData.GetWindowProcedureAddress, hwnd, msg, wParam, lParam)
End Function

objMapMemoryData.ReadMessage raises an event that is handled by the Form:


Friend Function ReadMessage(ByVal lParam As Long) As Boolean
‘SNIP: Copy memory around
RaiseEvent MapMemoryDataEvent
End Function

Private Sub objMapMemoryData_MapMemoryDataEvent()
‘SNIP: Process event here
End Sub