본문 바로가기

work/vb

SendMessage값을 VB에서 받는 방법

Option Explicit

Public lpPrevWndProc As Long
Public lHwnd         As Long

Public Const GWL_WNDPROC = (-4)
Public Const WM_COPYDATA = &H4A

Public Type COPYDATASTRUCT
   dwData As Long
   cbData As Long
   lpData As Long
End Type

Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (hpvDest As Any, hpvSource As Any, ByVal cbCopy 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
Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long

Public Sub pHook()
   lpPrevWndProc = SetWindowLong(lHwnd, GWL_WNDPROC, AddressOf fWindowProc)
   Debug.Print lpPrevWndProc
End Sub

Sub pReceiveMsg(lParam As Long, wParam As Long)
   Dim sString As String
   Dim cds     As COPYDATASTRUCT
   Dim buf(1 To 255) As Byte
   Call CopyMemory(cds, ByVal lParam, Len(cds))
   Call CopyMemory(buf(1), ByVal cds.lpData, cds.cbData)
MsgBox cds.dwData
   sString = StrConv(buf, vbUnicode)
   sString = Left$(sString, InStr(1, sString, Chr$(0)) - 1)
   VBFrm.Text2 = sString
End Sub

Public Sub pUnhook()
   Call SetWindowLong(lHwnd, GWL_WNDPROC, lpPrevWndProc)
End Sub

Function fWindowProc(ByVal hw As Long, ByVal uMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
   If uMsg = WM_COPYDATA Then Call pReceiveMsg(lParam, wParam)
   fWindowProc = CallWindowProc(lpPrevWndProc, hw, uMsg, wParam, lParam)
End Function
=============
Private Sub Form_Load()
   lHwnd = Me.hwnd
   Call pHook
End Sub

Private Sub Form_Unload(Cancel As Integer)
   Call pUnhook
End Sub