MarshalAs COPYDATASTRUCT and SendMessage

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dvanmil
    New Member
    • Jan 2010
    • 2

    MarshalAs COPYDATASTRUCT and SendMessage

    I am having problems with Window Messages. I want to send the handle of a VB.NET winform to a VB6 application. The code I have used seems to work ok, since the message arrives at the VB6 app. However, I have a problem that sometimes I get an error stating that it is not possilbe to read or write to the memory and that memory might be corrupt.
    I have no idea what is causing this problem as I think I release the memory at the end of my procedure.

    I have provided the code in hope that someone else might have some insights in this problem.

    Code:
    Imports System.Runtime.InteropServices
    Imports System.Security
        Public Class WindowMessages
    
    #Region "Constants"
            Const WM_COPYDATA = &H4A
            Const LMEM_FIXED As Integer = &H0
            Const LMEM_ZEROINIT As Integer = &H40
            Const LPTR As Integer = (LMEM_FIXED Or LMEM_ZEROINIT)
    #End Region
    
    #Region "Dll import"
            <DllImport("user32.dll", EntryPoint:="SendMessageA", CallingConvention:=CallingConvention.StdCall, CharSet:=CharSet.Ansi)> _
            Private Shared Function SendMessage(ByVal hwnd As UInteger, ByVal Msg_Const As UInteger, ByVal wParam As UInteger, ByVal lParam As UInteger) As UInteger
            End Function
    
    #End Region
    
            <MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst:=255)>
            Private Shared text As String
    
            <StructLayout(LayoutKind.Sequential)>
            Public Structure COPYDATASTRUCT
                Public dwData As IntPtr   ' Use this to identify your message
                Public cbData As Integer   ' Number of bytes to be transferred
                Public lpData As IntPtr   ' Address of data
            End Structure
    
            Public Shared Sub SendDataMsg(ByVal statusText As String, ByVal lngToHwnd As IntPtr, ByVal lngFromHwnd As IntPtr)
                text = String.Copy(statusText)
    
                Dim oCDS As New COPYDATASTRUCT()
    
                oCDS.cbData = (text.Length + 1) 
                oCDS.lpData = Marshal.StringToHGlobalUni(text)
                oCDS.dwData = 3
                Dim lParam As IntPtr = Marshal.AllocHGlobal(oCDS.cbData)
                Marshal.StructureToPtr(oCDS, lParam, False)
    
                Call SendMessage(lngToHwnd, WM_COPYDATA, lngFromHwnd, lParam)
    
                Marshal.FreeHGlobal(oCDS.lpData)
                Marshal.FreeHGlobal(lParam)
    
            End Sub
    
        End Class
Working...