Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sendmessage from VB6 to vb.NET problem

Status
Not open for further replies.

Elgerm

Programmer
Aug 24, 2005
2
NL
I'm trying to send a windows message from vb6 to a vb.net app. The problem is that I can recieve a message, but the string I send with it is not recieved correctly by the vb.net app. When I try to put it back into a string again I get garbage.

Here is some code from the sending app (vb6):
Code:
Private Sub cmdSendData_Click()
Dim sString As String
Dim lHwnd   As Long
Dim cds     As COPYDATASTRUCT
Dim buf(1 To 255) As Byte

sString = Trim$(txtString)
If sString = "" Then Exit Sub
'
' Get the handle of the target application's visible window.
'
lHwnd = FindWindow(vbNullString, cWINDOW_TITLE)
'
' Copy the string into a byte array,
' converting it to ASCII. Assign lpData
' the address of the byte array.
'
Call CopyMemory(buf(1), ByVal sString, Len(sString))
With cds
    .dwData = 3
    .cbData = Len(sString) + 1
    .lpData = VarPtr(buf(1))
End With
'
' Send the string.
'
Call SendMessage(lHwnd, WM_COPYDATA, Me.hwnd, cds)
End Sub

And here is the recieving app(vb.net):
Code:
  Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
    If m.Msg = MainForm.WM_COPYDATA Then
      Dim data As CopyData
      Dim message As String

      ' get the data...
      data = CType(m.GetLParam(GetType(CopyData)), CopyData)
      message = Marshal.PtrToStringAuto(data.lpData, data.cbData \ Marshal.SystemDefaultCharSize)

      ' add the message
      Messages.Items.Add(String.Format("{0}: {1}", DateTime.Now.ToShortTimeString(), message))

      ' let them know we processed the message...
      m.Result = New IntPtr(1)
    Else
      MyBase.WndProc(m)
    End If
  End Sub

  Private Const WM_COPYDATA As Integer = &H4A

  <StructLayout(LayoutKind.Sequential)> _
  Private Structure CopyData
    Public dwData As IntPtr
    Public cbData As Integer
    Public lpData As IntPtr
  End Structure

If I send the same message from a vb.net app then everything works.
Can anyone tell me what I'm doing wrong?

Thanks!
 
ok fixed it!

changes (in the .net code):

Code:
'message = Marshal.PtrToStringAuto(data.lpData, data.cbData \   Marshal.SystemDefaultCharSize)
Dim B(255) As Byte
Marshal.Copy(data.lpData, B, 0, 255)
message = System.Text.Encoding.Default.GetString(B)

this is really handy when you're stuck with old vb6 apps and you're slowly migrating to vb.net.


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top