VB.NET通过Postmessage发送字符串

时间:2013-06-07 06:51:14

标签: vb.net string postmessage

好吧,这个问题长期困扰着我。

我有服务的代码,它通过PostMessage将字符串传递给客户端:

 Public Sub SendToClient(msgs As String, types As Integer, hwnd As Long)

        postMessage(hwnd, 0, Nothing, msgs)

    End Sub

然后我有接收字符串的客户端:

 Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
        If (m.Msg = 0) Then
            Dim a as string
            a = Marshal.PtrToStringAuto(m.LParam)
           end if
        MyBase.WndProc(m)
    End Sub

但是,客户端有时会发送错误或一些混乱的二进制数据,甚至只是一个空白字符串。顺便说一句,m.LParam是一个数字。

有人可以告诉我通过postmessage发送/接收字符串的正确方法。

1 个答案:

答案 0 :(得分:0)

我这样做:

Public Sub SendMessageToApp(ByVal NombreVentana As String, ByVal Mensaje As String, ByVal sender As Form)
        Dim hWnd As IntPtr
        Dim mCopyData As COPYDATASTRUCT

        hWnd = CType(FindWindow(Nothing, NombreVentana), IntPtr)
        Dim message As New System.Text.StringBuilder

        If (CInt(hWnd) <> 0) Then

            message.Append(Mensaje)

            Dim pCopyData As IntPtr = Marshal.AllocHGlobal(message.Length() + 40)


            mCopyData.lpData = Marshal.StringToHGlobalAnsi(message.ToString)
            mCopyData.cbData = message.Length
            mCopyData.dwData = CType(_messageID, IntPtr)
            Marshal.StructureToPtr(mCopyData, pCopyData, False)

            SendMessage(hWnd, WM_COPYDATA, CInt(sender.Handle), pCopyData)
            Marshal.FreeHGlobal(mCopyData.lpData)
            Marshal.FreeHGlobal(pCopyData)

        End If
    End Sub

接收窗口:

Declarations and definitions:

 Const WM_COPYDATA As Integer = 74
    Const SIG_LENGTH As Integer = 36
    Const MAX_COPY_LENGTH As Integer = 128
    Const SigConnect As String = "F7B82657-BD18-4ee6-B182-78721293821C"
    Dim CDCount As Integer

    Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" _
(ByVal lpClassName As String, ByVal lpWindowName As String) As Integer

    Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _
    (ByVal hwnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As Integer, _
    ByVal lParam As IntPtr) As Integer

    Dim hWndSender As Integer
    Private Const _messageID As Integer = 10

    'Estructura obligatoria para poder utilizar el API CopyData
    <StructLayout(LayoutKind.Sequential)> _
    Private Structure COPYDATASTRUCT
        Public dwData As IntPtr
        Public cbData As Integer
        Public lpData As IntPtr
    End Structure

Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)

        If m.Msg = WM_COPYDATA Then
            Dim Estructura As COPYDATASTRUCT
            Dim tipo As Type = Estructura.GetType
            Dim message As String

            Estructura = CType(m.GetLParam(GetType(COPYDATASTRUCT)), COPYDATASTRUCT)

            'Here you get the message
            message = Marshal.PtrToStringAnsi(Estructura.lpData, Estructura.cbData)

        End If